PHP、MySQL、jQuery、AJAX: json数据返回正确的响应,但前端返回错误。

时间:2022-10-08 09:11:38

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:

我有一个用户注册表。我正在通过AJAX进行服务器端验证。对我的问题的快速总结是,在验证两个字段时,会在第二个字段验证中得到错误。如果我注释第一个字段,那么第二个字段不会显示任何错误。它有这种奇怪的行为。更多的细节如下:

The HTML, JS and Php code are below:

HTML、JS和Php代码如下:

HTML FORM:

HTML表单:

<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:

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代码:

<?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:

只要我在check_ajax2中验证$_POST['email']和$_POST['confirm_email']。对confirm_email字段的验证总是返回一个错误。然而,由于我对Firebug的了解有限,当我在字段中输入电子邮件和confirm_email时,我发现以下是我的回复:

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

回答1:{“成功”:“y”、“msg_email”:“电子邮件可用”}

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

回复2:{"成功":"y","msg_email":"Email available"}{"success":"n","msg_confirm_email":"Email和Confirm Email不匹配"}

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.

尽管响应2显示我们正在通过msg_confirm_email接收正确的消息,但在前端,警告“一些错误”正在弹出(我已经激活了调试警报)。我花了48个小时尽可能地修改代码的每个部分,但几乎没有成功。奇怪的是,如果我完全注释$_POST['email']字段的验证,那么$_POST['confirm_email']字段的验证显示正确,没有任何错误。如果我启用它,它正在正确地验证电子邮件字段,但是当它到达验证confirm_email字段的点时,它再次显示错误。

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.

我还尝试在check_ajax2中重命名success变量。为$_POST['email']和$_POST['confirm_email']提供其他不同名称的php页面,但没有成功。我将在check_ajax2中添加更多的字段并进行验证。php页面。因此,我不打算使用不同的ajax页面来验证每个字段(我认为这样做并不明智)。我不是jquery或AJAX专家,所以非常感谢您为解决这个问题提供的所有帮助。

Thank you in advance.

提前谢谢你。

1 个解决方案

#1


2  

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

如果HTTP状态代码指示错误,以及响应解析失败,则将调用错误处理程序。

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/.

我认为您的错误处理程序在收到响应2时被调用,因为{“成功”:“y”、“msg_email”:“Email available”}{“success”:“n”、“msg_confirm_email”:“Email和确认邮件不匹配。”}不是有效的JSON。您可以使用: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中,可以在顶部定义$response_object数组,在底部打印json_encode($response_object):

<?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.

注意,我添加了对mysql_real_escape_string的调用,以帮助防止SQL注入。

#1


2  

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

如果HTTP状态代码指示错误,以及响应解析失败,则将调用错误处理程序。

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/.

我认为您的错误处理程序在收到响应2时被调用,因为{“成功”:“y”、“msg_email”:“Email available”}{“success”:“n”、“msg_confirm_email”:“Email和确认邮件不匹配。”}不是有效的JSON。您可以使用: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中,可以在顶部定义$response_object数组,在底部打印json_encode($response_object):

<?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.

注意,我添加了对mysql_real_escape_string的调用,以帮助防止SQL注入。