Visualizzazione dei risultati da 1 a 9 su 9
  1. #1
    Utente di HTML.it
    Registrato dal
    Mar 2008
    Messaggi
    46

    gestire, inserire dati checkbox con ajax e php

    Salve, ho un form sintetizzandolo:
    <form action="" method="post" id="cForm" > <input type='checkbox' id='products' name='products[]' value='1'> <input type='checkbox' id='products' name='products[]' value='2'> <input type='checkbox' id='products' name='products[]' value='3'> <input type='checkbox' id='products' name='products[]' value='4'> <input type='checkbox' id='products' name='products[]' value='5'>

    viene verificato da un file js con ajax:
    ----------------------------------------------------------------------
    funzione control.js
    ----------------------------------------------------------------------

    var retval=0;
    function validateFields() {
    var frmEl = document.getElementById('cForm');
    var strCC = document.getElementById('selfCC');
    var strCode = document.getElementById('strvercode');
    var posEmail = document.getElementById('email');
    var posName = document.getElementById('firstName');
    var posLastName = document.getElementById('lastName');
    var products = document.getElementById('products');
    var hostname = document.getElementById('hostname');
    var ip = document.getElementById('ip');
    var username = document.getElementById('username');
    var strCode = document.getElementById('strvercode');

    var at = document.getElementById("email").value.indexOf("@" );

    var whiteSpace = /^[\s]+$/;
    if ( posText.value == '' || whiteSpace.test(posText.value) ) {
    alert("Devi inserire un messaggio!!.\nMessage field is required !");

    }

    else if ( posLastName.value == '' ) {
    alert("Devi inserire un cognome.\nlast Name field is required !");

    }
    else if ( posName.value == '' ) {
    alert("Devi inserire un nome.\nName field is required !");

    }
    else if (at==-1)
    {
    alert("Devi inserire una Email valida!\nYou 've insert a valid email address !");

    }
    else if ( posEmail.value == '' ) {
    alert("Devi inserire una Email valida!\nYou 've to insert a valid email address.");

    }



    else if ( posEmail.value == '' && strCC.checked == true ) {
    alert("PerchÚ stai cercando di usare il CC te senza inserire una e-mail valida?");
    alert("Solo per quello...");
    alert("Sto eliminando tutti i campi!");
    frmEl.reset();
    alert("Ecco. Soddisfatto.");
    alert("Adesso partiamo!");
    posName.focus();
    }
    else {
    fetchvalue();


    if ( strCode.value == '' || whiteSpace.test(strCode.value) )
    {
    alert("Codice di verifica non corrispondente");
    return false;

    }else
    {
    retval=retval.toUpperCase();
    if(strCode.value==retval)
    {
    sendPosEmail();
    }
    else
    {
    alert("Codice di verifica non corrispondente");
    return false;
    }

    }
    }
    }
    function sendPosEmail () {
    var success = document.getElementById('emailSuccess');
    var strCC = document.getElementById('selfCC');
    var strCode = document.getElementById('strvercode');
    var posEmail = document.getElementById('email');
    var posName = document.getElementById('firstName');
    var posLastName = document.getElementById('lastName');
    var hostname = document.getElementById('hostname');
    var products = document.getElementById('products');
    var ip = document.getElementById('ip');
    var username = document.getElementById('username');
    var page = "xmlHttpRequestpron.php?contact=true&xml=true" ;

    showContactTimer(); // quickly begin the load bar
    success.style.display = 'none'; // hide the success bar (incase this is a multi-email

    // convert (&, +, =) to string equivs. Needed so URL encoded POST won't choke.
    var str1 = posName.value;
    str1 = str1.replace(/&/g,"**am**");
    str1 = str1.replace(/=/g,"**eq**");
    str1 = str1.replace(/\+/g,"**pl**");
    var str2 = posEmail.value;
    str2 = str2.replace(/&/g,"**am**");
    str2 = str2.replace(/=/g,"**eq**");
    str2 = str2.replace(/\+/g,"**pl**");
    var str11 = posLastName.value;
    str11 = str11.replace(/&/g,"**am**");
    str11 = str11.replace(/=/g,"**eq**");
    str11 = str11.replace(/\+/g,"**pl**");

    var str31 = ip.value;
    str31 = str31.replace(/&/g,"**am**");
    str31 = str31.replace(/=/g,"**eq**");
    str31 = str31.replace(/\+/g,"**pl**");
    var str32 = hostname.value;
    str32 = str32.replace(/&/g,"**am**");
    str32 = str32.replace(/=/g,"**eq**");
    str32 = str32.replace(/\+/g,"**pl**");
    var str33 = products.value;
    str33 = str33.replace(/&/g,"**am**");
    str33 = str33.replace(/=/g,"**eq**");
    str33 = str33.replace(/\+/g,"**pl**");

    var stuff = "selfCC="+strCC+"&posName="+str1+"&posEmail="+str2 +"&posLastName="+str11+"&ip="+str31+"&hostname="+s tr32+"&products="+str33;
    loadXMLPosDoc(page,stuff)
    }
    function showContactTimer () {
    var loader = document.getElementById('loadBar');
    loader.style.display = 'block';
    sentTimer = setTimeout("hideContactTimer()",6000);
    }

    function hideContactTimer () {
    var loader = document.getElementById('loadBar');
    var success = document.getElementById('emailSuccess');
    var precontactFormArea = document.getElementById('precontactFormArea');
    var fieldArea = document.getElementById('contactFormArea');
    var inputs = fieldArea.getElementsByTagName('input');
    var inputsLen = inputs.length;
    var tAreas = fieldArea.getElementsByTagName('textarea');
    var tAreasLen = tAreas.length;
    // Hide the load bar alas! Done Loading
    loader.style.display = "none";
    fieldArea.style.display = "none";
    precontactFormArea.style.display = "none";
    success.style.display = "block";
    success.innerHTML = '<strong style="color:green;">'+grabPosXML("confirmation")+ '[/b]';

    // Now Hijack the form elements
    for ( i=0;i<inputsLen;i++ ) {
    if ( inputs[i].getAttribute('type') == 'text' ) {
    inputs[i].value = '';
    }
    }
    for ( j=0;j<tAreasLen;j++ ) {
    tAreas[j].value = '';
    }
    }
    function fetchvalue()
    {

    var xmlHttp;
    try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
    // Internet Explorer
    try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
    try
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e)
    {
    alert("Your browser does not support AJAX!");
    return false;
    }
    }
    }
    xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
    {

    retval= xmlHttp.responseText;

    }
    }
    xmlHttp.open("GET","scripts/getsession.php",true);
    xmlHttp.send(null);

    }

    function ajaxContact() {
    var frmEl = document.getElementById('cForm');
    addEvent(frmEl, 'submit', validateFields, false);
    frmEl.onsubmit = function() { return false; }
    }
    addEvent(window, 'load',ajaxContact, false);

    i dati vengono poi inviati al :
    ----------------------------------------
    xmlHttpRequestpron.php
    ----------------------------------------

    <?php
    // change the 4 variables below
    require_once("../config/config.php");
    $yourName = 'xxx';
    $yourEmail = 'xxxxx@xxxxxx.it';
    $yourSubject = 'Replay ';
    $referringPage = 'http://www.xxxx.it/contact.php';
    // no need to change the rest unless you want to. You could add more error checking but I'm gonna do that later in the official release

    header('Content-Type: text/xml');
    echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';

    echo '<resultset>';

    function cleanPosUrl ($str) {
    $nStr = $str;
    $nStr = str_replace("**am**","&",$nStr);
    $nStr = str_replace("**pl**","+",$nStr);
    $nStr = str_replace("**eq**","=",$nStr);
    return stripslashes($nStr);
    }

    if ( $_GET['contact'] == true && $_GET['xml'] == true && isset($_POST['posText']) ) {

    ----omissis-----
    //serializzo products[]
    $sql = mysql_query("INSERT INTO tabella VALUES('','".$leadID."','".cleanPosUrl(serialize($ _POST['products']))."','','','')") or die("Could not add to table ". mysql_error());
    ----omissis-----

    echo '
    <status>'.$posStatus.'</status>
    <confirmation>'.$posConfirmation.'</confirmation>
    <regarding>'.cleanPosUrl($_POST['posRegard']).'</regarding>
    ';
    }

    echo' </resultset>';

    ?>
    Non riesco a gestire ed inserire i dati dei checkbox .
    Come si gestiscono gli array con ajax in questo modo?
    Grazie

  2. #2
    Non ho letto (per ovvi motivi) tutto il codice che hai inserito.

    Ma quello che posso consigliarti è:

    Ad ogni checkbox, assegna una funzione all'OnClick che ti aggiorna un campo hidden, con il valore di quel checkbox.

    Poi ti basterà controllare quel campo hidden per verificare il valore di quella checkbox.

    Almeno io faccio così quando devo passarlo ad ajax.

  3. #3
    Utente di HTML.it
    Registrato dal
    Mar 2008
    Messaggi
    46

    in che modo?

    Originariamente inviato da Samleo
    Non ho letto (per ovvi motivi) tutto il codice che hai inserito.

    Ma quello che posso consigliarti è:

    Ad ogni checkbox, assegna una funzione all'OnClick che ti aggiorna un campo hidden, con il valore di quel checkbox.

    Poi ti basterà controllare quel campo hidden per verificare il valore di quella checkbox.

    Almeno io faccio così quando devo passarlo ad ajax.
    scusa aggiorna in che senso?
    non ho capito cosa vuoi intendere....

  4. #4
    Ipotizzando che tu utilizzi Prototype, potresti fare una cosa del genere:

    Codice PHP:
    <input type='checkbox' onclick="$('valcheck').value='1'" Check 1

    <input type='hidden' id='valcheck' name='valcheck' /> 
    Poi in fase di controllo dei campi, ti basta controllare il campo valcheck per sapere cosa hanno scelto nei checkbox!

    Chiaro ora?

  5. #5
    Utente di HTML.it
    Registrato dal
    Mar 2008
    Messaggi
    46

    si ok

    Originariamente inviato da Samleo
    Ipotizzando che tu utilizzi Prototype, potresti fare una cosa del genere:

    Codice PHP:
    <input type='checkbox' onclick="$('valcheck').value='1'" Check 1

    <input type='hidden' id='valcheck' name='valcheck' /> 
    Poi in fase di controllo dei campi, ti basta controllare il campo valcheck per sapere cosa hanno scelto nei checkbox!

    Chiaro ora?
    si ma non saprei come inserirlo nella mia funzione...

  6. #6
    Non devi inserirlo nella funzione, devi inserirlo nell'HTML.

    Poi nella funzione controlli il campo con id vacheck come se fosse un comune campo di testo!

  7. #7
    Utente di HTML.it
    Registrato dal
    Mar 2008
    Messaggi
    46

    non sono pratico di jquery...

    Originariamente inviato da Samleo
    Non devi inserirlo nella funzione, devi inserirlo nell'HTML.

    Poi nella funzione controlli il campo con id vacheck come se fosse un comune campo di testo!
    non sarei pratico di jquery....

  8. #8
    E chi ha parlato di jquery...avevo detto prototype.

    In ogni caso, basta sostituire il $ con document.getElementById

  9. #9
    Utente di HTML.it L'avatar di Luke70
    Registrato dal
    Jul 1999
    Messaggi
    767
    A parte il fatto che la domanda riguarda Javascript e non PHP, credo che tutto sarebbe più facile se utilizzassi un framework javascript che gestisce da solo l'invio con ajax della form.

    In particolare ti suggerisco mootools con il quale la cosa è piuttosto banale.

    L'idea dei campi hidden mi sembra, in ogni caso, una complicazione inutile (a parte che lo script proposto non tiene conto del fatto che i checkbox possono anche essere delezionato dopo essere stato selezionato): invece di inviare il valore del campo hidden tanto vale verificare al momento se la checkbox è selezionata.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.