views:

721

answers:

1

Hi all,

I have a user registration form. I am doing server side validation on the fly via AJAX. The quick summary of my problem is that upon validating 2 fields, I get error for the second field validation. If I comment first field, then the 2nd field does not show any error. It has this weird behavior. More details below:

The HTML, JS and Php code are below:

HTML FORM:

<form id="SignupForm" action="">
            <fieldset>
                <legend>Free Signup</legend>
                <label for="username">Username</label>
                <input name="username" type="text" id="username" /><span id="status_username"></span><br />
                <label for="email">Email</label>
                <input name="email" type="text" id="email" /><span id="status_email"></span><br />
                <label for="confirm_email">Confirm Email</label>
                <input name="confirm_email" type="text" id="confirm_email" /><span id="status_confirm_email"></span><br />
            </fieldset>
            <p>
                <input id="sbt" type="button" value="Submit form" />
            </p>    

            </form>

JS:

<script type="text/javascript">

$(document).ready(function()
{   

  $("#email").blur(function() 
    { 
        var email = $("#email").val();
        var msgbox2 = $("#status_email");

        if(email.length > 3)
        {           
            $.ajax({  
                type: 'POST',       
                url: 'check_ajax2.php',         
                data: "email="+ email,  
                dataType: 'json',
                cache: false,                           
                success: function(data)
                {                     
                        if(data.success == 'y')
                        {   
                            alert('Available');
                        }  
                        else  
                        {  
                            alert('Not Available');
                        }     
                }
            }); 
        }       

        return false;
    }); 


    $("#confirm_email").blur(function() 
    { 
        var confirm_email = $("#confirm_email").val();
        var email = $("#email").val();
        var msgbox3 = $("#status_confirm_email");           

        if(confirm_email.length > 3)
        {

            $.ajax({  
                type: 'POST',       
                url: 'check_ajax2.php',         
                data: 'confirm_email='+ confirm_email + '&email=' + email,  
                dataType: 'json',
                cache: false,                           
                success: function(data)
                {     
                        if(data.success == 'y')
                        {   
                            alert('Available');
                        }  
                        else  
                        {  
                            alert('Not Available');
                        }     

                }
                , error: function (data)
                 {
                    alert('Some error');
                 }

            }); 
        }       

        return false;
    });           
}); 


</script>

PHP code:

<?php //check_ajax2.php


if(isset($_POST['email']))
{
    $email = $_POST['email'];


    $res = mysql_query("SELECT uid FROM members WHERE email = '$email' ");
    $i_exists = mysql_num_rows($res);

    if( 0 == $i_exists )
    {
        $success = 'y';
        $msg_email = 'Email available';
    }
    else
    {
        $success = 'n';
        $msg_email = 'Email is already in use.</font>';
    }

    print json_encode(array('success' => $success, 'msg_email' => $msg_email)); 
}

if(isset($_POST['confirm_email']))
{
    $confirm_email = $_POST['confirm_email'];
    $email = ( isset($_POST['email']) && trim($_POST['email']) != '' ? $_POST['email'] : '' );



    $res = mysql_query("SELECT uid FROM members WHERE email = '$confirm_email' ");
    $i_exists = mysql_num_rows($res);


    if( 0 == $i_exists ) 
    {
        if( isset($email) && isset($confirm_email) &&  $email == $confirm_email )
        {
            $success = 'y';
            $msg_confirm_email = 'Email available and match';
        }
        else
        {
            $success = 'n';
            $msg_confirm_email = 'Email and Confirm Email do NOT match.';
        }       
    }
    else
    {
        $success = 'n';
        $msg_confirm_email = 'Email already exists.';
    }

    print json_encode(array('success' => $success, 'msg_confirm_email' => $msg_confirm_email)); 
}

?>

THE PROBLEM:

As long as I am validating the $_POST['email'] as well as $_POST['confirm_email'] in the check_ajax2.php file, the validation for confirm_email field always returns an error. With my limited knowledge of Firebug, however, I did find out that the following were the responses when I entered email and confirm_email in the fields:

RESPONSE 1: {"success":"y","msg_email":"Email available"}

RESPONSE 2: {"success":"y","msg_email":"Email available"}{"success":"n","msg_confirm_email":"Email and Confirm Email do NOT match."}

Although the RESPONSE 2 shows that we are receiving the correct message via msg_confirm_email, in the front end, the alert 'Some error' is popping up (I have enabled the alert for debugging). I have spent 48 hours trying to change every part of the code wherever possible, but with only little success. What is weird about this is that if I comment the validation for $_POST['email'] field completely, then the validation for $_POST['confirm_email'] field is displaying correctly without any errors. If I enable it back, it is validating email field correctly, but when it reaches the point of validating confirm_email field, it is again showing me the error.

I have also tried renaming success variable in check_ajax2.php page to other different names for both $_POST['email'] and $_POST['confirm_email'] but no success. I will be adding more fields in the form and validating within the check_ajax2.php page. So I am not planning on using different ajax pages for validating each of those fields (and I don't think it's smart to do it that way). I am not a jquery or AJAX guru, so all help in resolving this issue is highly appreciated.

Thank you in advance.

+1  A: 

The error handler is called if the HTTP status code is indicative of an error as well as when parsing of the response fails.

I think that your error handler is being called upon receipt of RESPONSE 2 because {"success":"y","msg_email":"Email available"}{"success":"n","msg_confirm_email":"Email and Confirm Email do NOT match."} is not valid JSON. You can use the validator at: http://jsonlint.com/.

In your PHP, you could define a $response_object array at the top and print json_encode($response_object) at the bottom:

<?php //check_ajax2.php

$response_object = array('success' => 'y');

if(isset($_POST['email']))
{
    $email = $_POST['email'];


    $res = mysql_query("SELECT uid FROM members WHERE email = '" . mysql_real_escape_string($email)  . "' ");
    $i_exists = mysql_num_rows($res);

    if( 0 == $i_exists )
    {
        $msg_email = 'Email available';
    }
    else
    {
        $response_object['success'] = 'n';
        $msg_email = 'Email is already in use.';
    }

    $response_object['msg_email'] = $msg_email; 
}

if(isset($_POST['confirm_email']))
{
    $confirm_email = $_POST['confirm_email'];
    $email = ( isset($_POST['email']) && trim($_POST['email']) != '' ? $_POST['email'] : '' );



    $res = mysql_query("SELECT uid FROM members WHERE email = '" . mysql_real_escape_string($confirm_email) . "' ");
    $i_exists = mysql_num_rows($res);


    if( 0 == $i_exists ) 
    {
        if( isset($email) && isset($confirm_email) &&  $email == $confirm_email )
        {
            $msg_confirm_email = 'Email available and match';
        }
        else
        {
            $response_object['success'] = 'n';
            $msg_confirm_email = 'Email and Confirm Email do NOT match.';
        }      
    }
    else
    {
        $response_object['success'] = 'n';
        $msg_confirm_email = 'Email already exists.';
    }

    $response_object['msg_confirm_email'] = $msg_confirm_email; 
}

print json_encode($response_object);

Note that I added calls to mysql_real_escape_string to help prevent SQL injection.

Daniel Trebbien
+1. Thank you so much for the solution, Daniel. It worked like a charm. Also I tried out the link that you gave me for validating the json response but when I hit the validate button, it's giving me the results as Parsing failed. I gave it an input of {"success":"y","msg_email":"Email available"}{"success":"n","msg_confirm_email":"Email and Confirm Email do NOT match."} .Did I do the right thing? Sorry, I am a total newbie to the link that you gave me and hence the question.
Devner
I'm glad it worked! Yes, you are doing the right thing. It says "Parsing failed" because the string `{"success":"y","msg_email":"Email available"}{"success":"n","msg_confirm_email":"Email and Confirm Email do NOT match."}` is not valid JSON. Basically, if the jsonlint website says "Parsing failed", then you know that jQuery will call your error handler.
Daniel Trebbien
Devner
Yes. PHP frameworks can help you to reduce the amount of validation code that you have to write. There are a couple of PHP frameworks that I would recommend investing the time to learn: CakePHP when your website is heavily database-driven (CRUD: Create, Read, Update and Delete) and CodeIgniter for an all-around good framework. It takes some time to learn them and set them up, but the benefits of a framework can be well worth the time invested, even if you only use a few of the features. See, for example, http://codeigniter.com/user_guide/libraries/form_validation.html
Daniel Trebbien
Hi Daniel, thank you very much for the link. PHP validation is somewhat manageable while it is JS validation that I am trying to really sort out. Are any links that may reference to shortening JS validation code available?
Devner
Since you are using patterns such as `msg_email` for the <input> with name `email`, `msg_username` for the <input> with name `username`, etc., I would iterate through the form, examining all <input>s and <select>s, and try to find a value in the response that was "msg_" concatenated with the field's `name`. If found, then attempt to find the <span> with id "status_" + field name to set its `innerHTML` using jQuery's `html`. Right now, you are not doing client-side validation, but if you decide to do this, then try implementing the framework's validation routines in Javascript.
Daniel Trebbien
Thanks for the idea. I shall try that.
Devner