Using AJAX to validate a form

  • Profile Image
    chiseled_images
    Asked on July 23, 2012 at 11:11 PM

    I've got the full source code for my form on my site.  The form is set to post to a page which will take the fields and insert the values into a database.  Pretty cut and dry.
    The issue I need help with is so that when the user presses submit, the 'account number' field is validated as a valid account in my clients database, before the form is submitted.  If the account is invalid, I want to form to not post to the next page.  Can someone point me in the right direction of a script to use to attach to the sumit button?
    thanks.

  • Profile Image
    liyam
    Answered on July 24, 2012 at 01:23 AM

    Hello chiseled_images.  Let me help you with this. 

    Can you share with us here the form ID that you're going to use and which part of the form should run the validation?

    Thanks.

  • Profile Image
    chiseled_images
    Answered on July 24, 2012 at 09:04 AM

    Form ID: 21833563039959
    The URL for my testing is here: http://chiseledimages.com/misc/test/
    I need it to validate the "account Number" field on submit.
    The key is that I want to validate the account number without my customer loosing all the information they've typed it.  

    thanks

    -Andy

  • Profile Image
    liyam
    Answered on July 24, 2012 at 09:52 AM

    Thank you for the details, Andy. 

    I'll come up with a quick script for your form.  I'll update you once I have it ready.

    Thank you for your patience.

  • Profile Image
    chiseled_images
    Answered on July 24, 2012 at 09:55 AM

    Liyam,
    Thanks so much! You guys are great.

    -Andy 

  • Profile Image
    liyam
    Answered on July 24, 2012 at 12:36 PM

    Hello Andy,

    You can download the script I created from this link.  It's a zip archive. 

    Some small instructions:
    ======================
    > Extract the file and dump the db_structure.sql on your database (if I'm not mistaken the name of the table in the dump is chiseled_images.  Simply rename that if you wish).

    > Open the db.php file and enter your db values including the table name in your database.

    > The form.php is already set for you to use (it's already set to your form ID).  Just modify it for your desired layout.
    ======================

    Here's a live demo of the cloned form:  http://liyam.comuf.com/jotform/chiseled_images/form.php

    You can try doing a submission and then using the account number for looking up.  Or you can try entering '12345' to see how the look-up with existing record works.

    If you have further questions, please let us know.

    Thanks.

  • Profile Image
    chiseled_images
    Answered on July 24, 2012 at 03:18 PM

    Thanks! I'm working on implementing it now.  I never expected you to just write it out for me.  You have saved me tons of time! 

  • Profile Image
    chiseled_images
    Answered on July 24, 2012 at 04:34 PM

    Liyam,
    Taking this a little farther.  Is there a way to pass a variable from the account_lookup.php back to the jQuery.
    So I tried this on the account_lookup.php
    [code]
    //mysql query to select field product ID if it's equal to the product ID that we check '
    $result = mysql_query('SELECT * FROM `'. chi_clients .'` WHERE `AccountNum` = "'. $acct .'"') or die(mysql_error());

    //get client name
    $numrows=mysql_num_rows($result);
    $row =  mysql_fetch_assoc($result);
    $name = $row['firstName'];
    [/code]

    and then this on the form page:
    [code]
    jQuery('#account_result').html('Hi ' + $name );
    [/code]

    Basically I want to take the name of the user from the database and then when they type their account number in it prints "Hi username".

    -------

    UPDATE
    I've made file client_name.php
    [code]

    <?php
    include("confff.php");
      mysql_connect( $host, $username, $password) or die(mysql_error());
    mysql_select_db($db_name);
        
    //get the username
    $acct = mysql_real_escape_string($_POST['acctnumber']);

    //get client name
    $query2 =mysql_query("SELECT * FROM chi_clients WHERE AccountNum='$acctNum'");
          $numrows=mysql_num_rows($query2);
        $row =  mysql_fetch_assoc($query2);    
            $name= $row['firstName'];
        echo $name   
            ?>

    [/code]

    and then modified the jQuery to this:
    [code]
    //get the username
            var acctnumber = jQuery('#input_26').val();
           
            //use ajax to run the check
            jQuery.post("account_lookup.php", { acctnumber: acctnumber },
           
                function(result){
                    //if the result is 1
                    if(result == 1){
                        //show that the username is invalid
                        jQuery('#account_result').html('<span class="is_available" style="color: #ff0000;">Account Number is invalid</span>');
                        document.getElementById('input_2').disabled = false;
                    }else{
                        //show that the username is valid
                        jQuery.post("client_name.php", { acctnumber: acctnumber },
                        function(name){
                        jQuery('#account_result').html('<span class="is_not_available"style="color: #ff0000;">Hi </span>' + name);
                        document.getElementById('input_2').disabled = true;       
                        //)}
                    }
            });

    [/code]

    I don't think i fully grasp how jQuery.post works.

  • Profile Image
    liyam
    Answered on July 24, 2012 at 11:07 PM

    I see that you have already placed an echo for the $name var. 

    Next, to make your javascript code print the name:  Remember that previously, we were printing 0 for a matching record and 1 for no matching record found for the result.  So this time, we'll use 0 if no matching record and 1 if there is a matching record in the condition

    function(result){
                    //if the result is 1
                    if(result < 1){
                        //show that the username is available
                        jQuery('#account_result').html('<span class="is_available"></span>');
                        document.getElementById('input_2').disabled = false;
                    }else{
                        //show that the username is NOT available
                        jQuery('#account_result').html('<span class="is_not_available" style="color: #ff0000;">Hello ' + result + '</span>');
                        document.getElementById('input_2').disabled = true;       
                    }
            });

    We use also the result as variable in javascript as this will be the one carrying the $name PHP variable.  Hope this clarifies your concerns.

    Please let us know if you have further questions.

    Thanks. :)

  • Profile Image
    chiseled_images
    Answered on July 24, 2012 at 11:35 PM

    Thanks. I actually just got it to work right before I got the email that you updated this thread.
    What I did was

    added a global var 'name'

    then add this:
    jQuery.post("client_name.php", { acctnumber: acctnumber },
                    function(result){   
                        name = result   
                        });

    and back in the original function(result) you wrote:did this:

    ...}else{
                        //show that the username is valid
                        //jQuery.post("client_name.php", { acctnumber: acctnumber },
                        //function(name){
                        jQuery('#account_result').html('<span class="is_not_available"style="color: #ff0000;">Hi ' + name + '</span>');

     

    works great!  Thanks for your help and direction with this.  Definitely learned something to store in my arsenal.

  • Profile Image
    chiseled_images
    Answered on July 25, 2012 at 11:19 AM

    Liyam,
    This is working great.  I just have found one issue.  My form is currently at: http://chiseledimages.com/misc/test/
    and Valid account numbers are from 301-333 to test with.

    I've added to the conditionals so that if they are using an account number it doesn't ask them to enter their name, email, or phone since all that should be on file in the database.  So even though it hides the fields it still searches the database and inputs the info in to those fields to show them after submission.

    Ok, so that part is working great (thanks to your help).  However one issue I have is that if someone tries an account number, and then switches to 'no' for account number, the email and phone fields are filled out.  I would rather avoid this so people don't go around trying random numbers to collect info.

    I treid modifying the conditions statement to:   JotForm.setConditions([{"type":"field","link":"Any","terms":[{"field":"27","operator":"equals","value":"Yes"}],"action":{"field":"3","visibility":"Hide"}}, {"type":"field","link":"Any","terms":[{"field":"27","operator":"equals","value":"Yes"}],"action":{"field":"11","visibility":"Hide"}}, {"type":"field","link":"Any","terms":[{"field":"27","operator":"equals","value":"Yes"}],"action":{"field":"12","visibility":"Hide"}}, {"type":"field","link":"Any","terms":[{"field":"27","operator":"equals","value":"No"}],"action":{"field":"26","visibility":"Hide"}}, {"type":"field","link":"Any","terms":[{"field":"27","operator":"equals","value":"No"}],"action":{"field":"11","value":" "}}, {"type":"field","link":"Any","terms":[{"field":"27","operator":"equals","value":"No"}],"action":{"field":"12","value":" "}}]);

    However field 11 (email) and 12(phone) still do not empty when they switch to "no".
    any ideas?

  • Profile Image
    chiseled_images
    Answered on July 25, 2012 at 09:28 PM

    well I still kind of wish I could have figured out the Conditions to work (if it's possible to do what I wanted)... however I got it to work once I realized that I didn't need those fields to post till after submit.  So now, the phone number and email aren't gathered from the DB and posted until after the user hits submit.  This keeps the info from being displayed until after submit. works like a charm.

  • Profile Image
    liyam
    Answered on July 25, 2012 at 10:25 PM

    It seems that you have figured this out.  Sorry for being late on looking on to this. 

    But if you have further questions, just let us know.

    Thanks and warm regards,

    Liyam

  • Profile Image
    chiseled_images
    Answered on July 31, 2012 at 02:32 PM

     

    I hope it's ok If I continue on this thread since it's the same idea and subject, just different form.

    Still working on the same project, I've added a page for me to be able to pull up my orders, and then want to be able to modify the orders in my database.  That's the easy part.

    The tricky part is that I want to be able to type in the Order Number and auto fill the fields with the current data in the table.  I thought I would be able to use the code that i used on the previous form and adjust, but it's just not working.

    Got that part (took a break, started from scaratch and it worked)

    New Question: How can I return an array from my jQuery.post.  I'd like to be able to fill out all the fields on the form from the databse.  So I'd like to use the order_details.php to return the name, job name, product, qty, notes, date in, and date out and then post that back to my jQuery to auto fill the form for me.

    thanks.

    formID=22117143069952
    URL: http://chiseledimages.com/misc/test/admin.php

    here is my order_detials.php:

    <?php
    include("confff.php");
      mysql_connect( $host, $username, $password) or die(mysql_error());
    mysql_select_db($db_name);
         
    //get the username
    $order = mysql_real_escape_string($_POST['ordernumber']);

    //get client name
    $query2 =mysql_query("SELECT * FROM chi_orders WHERE ordNum='$order'");

          $numrows=mysql_num_rows($query2);
        $row =  mysql_fetch_assoc($query2);    
            $name= $row['name'];
        echo $name    ;
        

            ?>


    thanks.

  • Profile Image
    liyam
    Answered on August 01, 2012 at 04:22 AM

    Hello Andy,

    If you wish to print an array, the variable $row is already an array result.

    Try adding a print_r($row); or var_dump($row); under echo $name;  Then take note of the keys in the array result.

    You will notice that if you do a print_r($row); or var_dump($row); will appear all the results of one row from your database, while the $row['name'] only tries to return the name key in an array.

    Now that you have the PHP array result, you should have it json encoded so that javascript will be able to read the array properly.  Here's what I did:  

    change these:

    $name= $row['name'];
    echo $name;

    With these:

    $js_array = json_encode($row);
    echo $js_array;
     

    Next:  going back to the javascript in the admin.php.  Since the look-up script echoes a string (although already encoded in json format), you should set the value to JSON so that it will be read as such. Check out the ones in bold:

    jQuery.post("order_details.php", { ordernumber: ordernumber },

    function(result){
                          var result = JSON.parse(result);
                    name = result
                    document.getElementById('input_3').value = result.name ;

      });

    To get the key of the JSON array, you just have to add the key after the result variable, separated by a dot [.] as highlighted above. 

    I know my explanation here is quite difficult to understand.  So if you need further clarification, just let me know.

    Thanks.

  • Profile Image
    chiseled_images
    Answered on August 01, 2012 at 11:17 AM

    worked like a charm.  I thought i'd use jSON but I wasn't having any luck.  You explanation filled the gaps perfecty.

    thanks again for your help.

  • Profile Image
    Lawrence Williams 
    Answered on April 15, 2017 at 10:45 AM

    Hello, I need help asap, I have a database that will collect data and then i need to be able to fill data on webforms from my mysql database. but i need to either auto send that data to a specific website or i need to be able to look up my customer and using a web browser, or a script, fill forms on other websites that i don't own , with data for that patient.  . please call me as I need to fix this asap 

    2392291137 or reply here and I hope i get it 

  • Profile Image
    AIDAN
    Answered on April 15, 2017 at 01:05 PM

    We will be addressing your request ASAP in this new thread: https://www.jotform.com/answers/1120171

    Thank you.