Visualizzazione dei risultati da 1 a 6 su 6
  1. #1
    Utente di HTML.it
    Registrato dal
    May 2010
    Messaggi
    144

    Passare variabili tra JS e PHP

    Ciao a tutti!
    Allora ho una domanda da porre perchè non riesco ad arrivare a capo di questo problema...

    Allora io ho un form in php che tramite js e ajax viene controllato dinamicamente.
    Ho una pagina php ch econtiene il form e le chiamate alle due pagine javascript...
    La pagina validate.js si occupa di prendere i vari dati del form e poi farne delle verifiche:
    validate.js
    Codice PHP:
    window.onload attachFormHandlers;

    function 
    attachFormHandlers()
    {
      
    // Make sure we're on a newer browser
        
    if (document.getElementsByTagName)
        { 
            var 
    objInput document.getElementsByTagName('input'); // get all input tags
            
    var form document.getElementById('form1'// get the form
        
                
    for (var iCounter=0iCounter<objInput.lengthiCounter++)
                {
                    
    objInput[iCounter].onchange = function(){return attach(this);} // attach the onchange event to each input tag
                
    }        
        
    form.onsubmit = function(){return validate();} // atttach the onsubmit to the form 
        
    }
    }


    function 
    attach(objInput)
    {
        
    sVal objInput.value//sVal is the value of the input field being validated
        
    var sFeedBack//feedback message sent back to the user
        
    var sFeedbackLoc =  objInput.getAttribute('message');
        
        if (
    objInput.getAttribute('required') == "true")
        {
            
    sFeedback validateRequired(sVal); //validateRequired() checks if it is invalid and sends back feedback
        
    }
        else 
    sFeedback "";
        
                
        if (
    sVal != ""//if the value is blank we don't need to validate.  If it is required, the word
            //"required"  will already be the feedback message from the validateRequired() function
        
    {
        
    // check the different validation cases (ie: email, phone, etc.)
            
    switch (objInput.getAttribute('validate'))
            {
                
                case 
    "email":
                    
    sFeedback validateEmail(sVal);
                    break;        
                case 
    "zip":
                    
    sFeedback validateZip(sVal);
                    break;
                case 
    "password":
                    
    sFeedback validatePassword(sVal);
                    break;
                case 
    "name":
                    
    sFeedback validateName(sVal);
                    break;
                case 
    "lastname":
                    
    sFeedback validateLastName(sVal);
                    break;
                
                
            }
        }
                
    // after validation is complete return the feedback 
        
    document.getElementById(sFeedbackLoc).innerHTML sFeedback;    
    }

    function 
    validateRequired(sVal)
    {
               if (
    sVal != ""//if it is rquired and blank then it is an error and continues to be required
            
    {
                return (
    "Thank You");
            }
            else 
            {
                
    gContinue false;
                return(
    "Required");
            }
    }



    function 
    validateEmail(sVal)
    {
        
    // our email regular expression ([url]http://www.regexlib.com[/url])
     
    var regex=/^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
     
        
    // do the comparison, if we have a match write thank you or else the email is invalid
        
    if (regex.test(sVal))
        {
            var 
    email sVal;
            return 
    email;
            
          return 
    "Thank You";
        }
        else
        {
          return 
    "Invalid Email Address";
        }
    }

    function 
    validatePhone(sVal)
    {
        
    // our phone regular expression
    // This expression is a very simplex expression that allows null values or 3 digits, dash, 
    //3 digits, dash, 4 digits. It validates a basic US phone number. Written by Jason N. Gaylord.([url]http://www.regexlib.com[/url])
    // Matches:       [555-555-1212], [123-456-7890]
     
    var regex=/^(\d{3}-\d{3}-\d{4})*$/;
     
        
    // do the comparison, if we have a match write thank you or else the email is invalid
        
    if (regex.test(sVal))
        {
          return 
    "Thank You";
        }
        else
        {
          return 
    "Invalid Phone";
        }
    }

    function 
    validateZip(sVal)
    {
        
    // our email regular expression
    //Javascript matches US zipcodes not allowing all zeros in first 5 or +4 ([url]http://www.regexlib.com[/url])
    // Matches:       [12345], [12345-6789], [123456789]
     
    var regex=/(^(?!0{5})(\d{5})(?!-?0{4})(-?\d{4})?$)/;
     
        
    // do the comparison, if we have a match write thank you or else the email is invalid
        
    if (regex.test(sVal))
        {
          return 
    "Thank You";
        }
        else
        {
          return 
    "Invalid ZipCode";
        }
    }

    function 
    validatePassword(sVal)

    //Description: The password's first character must be a letter, it must contain at least 4 characters
    //and no more than 15 characters and no characters other than letters, numbers and the underscore may be used
    //Matches:     [abcd], [aBc45DSD_sdf], [password] ([url]http://www.regexlib.com[/url])
     
    var regex=/^[a-zA-Z]\w{3,14}$/;
     
        
    // do the comparison, if we have a match write thank you or else the email is invalid
        
    if (regex.test(sVal))
        {
          return 
    "Thank You";
        }
        else
        {
          return 
    "Invalid Password";
        }
    }

    function 
    validateName(sVal)

    //This is the simplest RegEx for validating someone's name. The name can contain only alphabets(in either case) & 
    //should be of minimum length 4 & maximum length 32. Only white spaces are allowed apart from alphabets.
    //Matches:     [some body], [hey there], [hello] ([url]http://www.regexlib.com[/url])
     
    var regex=/^([a-zA-z\s]{4,32})$/;
     
        
    // do the comparison, if we have a match write thank you or else the email is invalid
        
    if (regex.test(sVal))
        {
          return 
    "Thank You";
        }
        else
        {
          return 
    "Invalid Name";
        }
    }

    function 
    validateLastName(sVal)

    //This is the simplest RegEx for validating someone's name. The name can contain only alphabets(in either case) & 
    //should be of minimum length 4 & maximum length 32. Only white spaces are allowed apart from alphabets.
    //Matches:     [some body], [hey there], [hello] ([url]http://www.regexlib.com[/url])
     
    var regex=/^([a-zA-z\s]{4,32})$/;
     
        
    // do the comparison, if we have a match write thank you or else the email is invalid
        
    if (regex.test(sVal))
        {
          return 
    "Thank You";
        }
        else
        {
          return 
    "Invalid Cognome";
        }

    Ok, ora c'è la pagina submitvalidate.js che si occupa principalmente di mandarmi l'errore se tutti i dati non sono stati inseriti correttamente. oppure mi ridirige ad inserisci_dati_form.php

    Codice PHP:
    var gErrors 0//number of errors is set to none to begin with

    function validate()
    {
    var 
    tables//variable which will become an array holding all elements with the td tagname

    // store all <td> elements in the tables array
    tables document.getElementsByTagName('td')

    //loop through all the <td> elements 
        
    for (i=0i<tables.lengthi++)
            {
            
    // if the class name of that td element is rules check to see if there are error warnings
            
    if (tables[i].className == "rules")
                {
                    
    //if there is a thank you or its blank then it passes
                    
    if (tables[i].innerHTML == 'Thank You' || tables[i].innerHTML == '' )
                    {
                    
    tables[i].style.color '#000000';//the color is changed to blank or stays black
                    
    }
                    else
                    {
                    
    gErrors gErrors 1//the error count increases by 1
                    
    tables[i].style.color '#ff0000';//error messages are changed to red
                    
    }
                }
            }
            
            if (
    gErrors 0){
                
    //if there are any errors give a message
                
    alert ("Assicurati che tutti i campi obbligatori siano compilati correttamente!");
                
    gErrors 0;// reset errors to 0
                
    return false;
            }
            
            else 
            {
                
    //alert("The Form Is Valid!");
                
    window.location 'inserisci_dati_form.php'
                
    return false;//set this to true in practice to allow the form to submit
            
    }
        


    Io però vorrei che alla pagina inserisci_dati_form.php inviassi in qualche modo i dati presi dal form per riceverli con post e lavorare con il database...
    Se fossi in php non avrei problemi... ma in js come faccio?
    Qualcuno mi da una mano???

    GRAZIE!

  2. #2
    Utente di HTML.it L'avatar di las
    Registrato dal
    Apr 2002
    Messaggi
    1,221
    sostituisci

    codice:
    window.location = 'inserisci_dati_form.php'
    con

    codice:
    document.forms["nomeTuoForm"].submit();
    poi metti nella action del form "inserisci_dati_form.php" e cambia il tipo di pulsante di invio da submit a button, aggiungendogli l'evento onClick="validate()"
    Il calcolatore è straordinariamente veloce, accurato e stupido.
    L'uomo è incredibilmente lento, impreciso e creativo.
    L'insieme dei due costituisce una forza incalcolabile.
    (Albert Einstein)

  3. #3
    Utente di HTML.it
    Registrato dal
    May 2010
    Messaggi
    144
    GRAZIE!!!
    Sei stato davvero grandissimo
    Solo un'altra cosa...
    Adesso ogni volta che inserisco un campo nel form, mi viene l'alert js: "Assicurati che tutti i campi obbligatori siano compilati correttamente!" che è in submitvalidate.js e si dovrebbe verificare solo quando clicco su "submit" (che ho messo di tipo button".
    E idem quando compilo tutti i dati obbligatori mi reindirizza all'altra pagina php senza che si clicchi su submit... in pratica ogni volta che si "seleziona" un input del form per compilarlo, entra in validate() nel file submitvalidate.js

    Ho provato a cambiare l'onclick in onsubmit, ma niente da fare, neanche onButton (non penso quest'ultimo esista )

    Come posso fare?

    Grazie tante!

  4. #4
    Utente di HTML.it L'avatar di las
    Registrato dal
    Apr 2002
    Messaggi
    1,221
    credo che dipenda da come vengono richiamate le funzioni dai campi del form, posta il codice del form.



    P.S. siamo un pò fuori tema rispetto alla sezione PHP, questo è puro javascript, forse ti conviene farti spostare
    Il calcolatore è straordinariamente veloce, accurato e stupido.
    L'uomo è incredibilmente lento, impreciso e creativo.
    L'insieme dei due costituisce una forza incalcolabile.
    (Albert Einstein)

  5. #5
    Utente di HTML.it
    Registrato dal
    May 2010
    Messaggi
    144
    Si, hai ragione, chiedo se per piacere mi possono spostare il post nella sezione correta JS...
    pensavo fosse più un problema di php...

    ecco il mio form
    Codice PHP:
    <form name="form1" id="form1" method="post" action="data_insert_vero.php" onClick="validate()" >


    <
    table width="400" border="0">
     <
    tr>
       <
    td width="86"><div class="formtext"Nome </div></td

         <
    td ><input type="text" name="name" tabindex="1" id="name" required="true" validate="name" message="namemsg" /></td>
        
        <
    td width="130"  class="rules" id ="namemsg">*</td>
    </
    tr>

    <
    tr>
       <
    td width="86"><div class="formtext"Cognome </div></td

         <
    td><input type="text" name="lastname" tabindex="1" id="lastname" required="true" validate="lastname" message="lastnamemsg" /></td>
        
        <
    td width="25"  class="rules" id ="lastnamemsg">*</td>
    </
    tr>

    <
    tr>
       <
    td width="86"><div class="formtext"Matricola </div></td

         <
    td><input type="text" name="matricola" tabindex="1" id="matricola" required="true"  message="matricolamsg" /></td>
        
        <
    td width="25"  class="rules" id ="matricolamsg">*</td>
    </
    tr>

    <
    tr>
       <
    td width="86"><div class="formtext"Email </div> </td>
       <
    td><input type="text" name="emailaddress" tabindex="2" id="emailaddress" required ="true" validate="email"message="emailaddressmsg"/></td>
       
       
       <
    td id="emailaddressmsg" width="25" class="rules">*</td>

     </
    tr>
     
     <
    tr>
       <
    td width="86"><div class="formtext"Password </div> </td

         <
    td><input type="password" name="password" tabindex="1" id="password" required="true" validate="password" message="passwordmsg" /></td>
        
        <
    td width="25"  class="rules" id ="passwordmsg">*</td>
    </
    tr>

     
        
    <
    tr>
       <
    td width="86"><div class="formtext"Indirizzo </div></td

         <
    td><input type="text" name="indirizzo" tabindex="1" id="indirizzo" required="false" message="indirizzomsg" /></td>
        
    </
    tr>

    <
    tr>
       <
    td width="86"><div class="formtext"Citt&aacute; </div></td

         <
    td><input type="text" name="citta" tabindex="1" id="citta" required="false" message="cittamsg" /></td>
        
    </
    tr>

    <
    tr>
       <
    td width="86"><div class="formtext"Cap </div> </td>

       <
    td><input type="text" name="zipcode" tabindex="2" id="zipcode" validate="zip" message="zipcodemsg"/></td>
           <
    td width="25"  class="rules" id ="zipcodemsg"></td>
     </
    tr>
     
     

    <
    tr>
       <
    td width="86"><div class="formtext"Telefono </div></td

         <
    td><input type="text" name="tel" tabindex="1" id="tel" required="false" validate="numeric" message="telmsg" /></td>
        <
    td width="25"  class="rules" id ="telmsg"></td>
    </
    tr>

    </
    table>






    <
    table width="400" border="0">
    <
    tr>
    <
    td width="87"> </td>
    <
    div class="inputsubmit"></div>

     <
    td><p align="left"><input type="button" name="Submit" value="Registrazione" tabindex="9" /></p>
       </
    td>
    </
    tr>  
      
    </
    table>

    </
    form

  6. #6
    Utente di HTML.it
    Registrato dal
    May 2010
    Messaggi
    144
    Ok ho risolto, allora il submit bisogna metterlo di tipo submit e e poi si mette l' onSubmit... in effetti era una stupidata...

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 © 2024 vBulletin Solutions, Inc. All rights reserved.