PHP, MySQL, jQuery, AJAX: json data returns correct response but frontend returns error

Posted by Devner on Stack Overflow See other posts from Stack Overflow or by Devner
Published on 2010-05-27T18:15:35Z Indexed on 2010/05/27 19:01 UTC
Read the original article Hit count: 288

Filed under:
|
|
|
|

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.

© Stack Overflow or respective owner

Related posts about php

Related posts about jQuery