Ajax回调没有响应

时间:2013-03-16 15:56:12

标签: php jquery callback validation

我使用下面的脚本来检索回调结果,但是在提交表单时没有返回,下面的代码有什么问题?以及如何使用id='msg'将每个错误输出到div标签?

这是我的注册表格的完整脚本:

<script type="text/javascript">
$(document).ready(function() {

$('#wait').hide();
$('#wait').ajaxStart(function() {
    $(this).show();
}).ajaxComplete(function() {
    $(this).hide();
});

$('#btn_register').click(function(){
    var parameters = $('#register_form').serialize();
    //alert(parameters);
    $.ajax({
        url: 'request.php',
        type: 'POST',
        data: parameters,
        dataType: 'json',
        success: function(output_str){
            if(output_str == "error"){
                alert('Error: '+ output_str);

            }else{
                alert(output_str);
                //$('#result_msg').html(output_str);
            }
        },
        error: function(){
            console.log(arguments);
        }
    });

});

});
</script>

<div class="content">
<div>
    <div class="title-bar" align="center"><h2 class="title">Registration Form</h2></div>

    <div class="inner-wrap pad">
        <div id="msg"></div>
        <div align="center">
        <form action="" method="post" id="register_form" enctype="multipart/form-data">
        <table width="60%" border="0" cellspacing="1" cellpadding="5" class="tb">
          <tr>
            <td width="30%" class="r"><label for="email">Email</label></td>
            <td width="70%"><input type="text" id="email" name="email" maxlength="50" value="" autofocus autocomplete="off" /></td>
          </tr>
          <tr>
            <td class="r"><label for="password">Password</label></td>
            <td><input type="password" id="password" name="password" style="width:150px;" value="<?php echo isset($_POST['password']) ? $_POST['password'] : '' ?>" /></td>
          </tr>
          <tr>
            <td class="r"><label for="rpassword">Retype Password</label></td>
            <td><input type="password" id="rpassword" name="rpassword" style="width:150px;" value="<?php echo isset($_POST['rpassword']) ? $_POST['rpassword'] : '' ?>" /></td>
          </tr>
          <tr>
            <td class="r"><label for="fname">Full Name</label></td>
            <td><input type="text" id="fname" name="fname" maxlength="50" value="<?php echo isset($_POST['fname']) ? $_POST['fname'] : '' ?>" /></td>
          </tr>
          <tr>
            <td class="r"><label for="contact">Contact Number</label></td>
            <td><input type="text" id="contact" name="contact" maxlength="15" value="<?php echo isset($_POST['contact']) ? $_POST['contact'] : '' ?>" /></td>
          </tr>
          <tr>
            <td class="r"><label for="dob">Date of Birth</label></td>
            <td>
            <input type="text" id="dd" name="dd" style="width:24px;" maxlength="2" value="<?php echo isset($_POST['dd']) ? $_POST['dd'] : '' ?>" placeholder="dd" />&nbsp;/
            <input type="text" id="mm" name="mm" style="width:24px;" maxlength="2" value="<?php echo isset($_POST['mm']) ? $_POST['mm'] : '' ?>" placeholder="mm" />&nbsp;/
            <input type="text" id="yy" name="yy" style="width:40px;" maxlength="4" value="<?php echo isset($_POST['yy']) ? $_POST['yy'] : '' ?>" placeholder="yyyy" />
            </td>
          </tr>
          <tr>
            <td class="r"><label for="capcha"></label></td>
            <td>
            <div style="padding-bottom:3px;">
            <img id="captcha" src="inc/securimage/securimage_show.php" alt="CAPTCHA Image" />
            <a href="#" onclick="document.getElementById('captcha').src='inc/securimage/securimage_show.php?' + Math.random(); return false" class="capcha">Refresh</a>
            </div>
            <div><input type="text" name="ct_captcha" size="12" maxlength="8" id="capcha" style="width:100px;" /></div>
            </td>
          </tr>
          <tr>
            <td></td>
            <td><a href="javascript:void(0);" class="btn" id="btn_register">Proceed</a>&nbsp;<span id="wait"><img src="images/ajax-loader.gif" /></span></td>
          </tr>
        </table>
        </form>
        </div>
    </div>

</div>

request.php

<?php
include('connectdb.php');
include('functions.php');

$email = mysql_real_escape_string(strtolower(trim($_POST['email'])));
$password = mysql_real_escape_string(trim($_POST['password']));

$error = NULL;
if(!check_email_address($email)){
    $error .= "<li>Invalid Email Address";
}
if(empty($password) || strlen($password) < 0){
    $error .= "<li>Invalid Password";
}

// if found invalid input
if(!empty($error)){
    $output_str = "error";
}else{
    $output_str = "No Error";   
}


echo json_encode($output_str);

?>

感谢。

更新:

控制台错误:

[Object { readyState=

4

,  responseText=

"<br />\n<b>Notice</b>:  ...<b>14</b><br />\n"error""

,  status=

200

,  more...}, 

"parsererror"

, 

SyntaxError: JSON.parse: unexpected character
[Break On This Error]   

return window.JSON.parse( data );

jquery-1.7.2.js (line 564)

]


0
Object { readyState=

4

, responseText=

"<br />\n<b>Notice</b>:  ...<b>14</b><br />\n"error""

, status=

200

, more...}

1


"parsererror"


2


SyntaxError: JSON.parse: unexpected character
[Break On This Error]   

return window.JSON.parse( data );

jquery-1.7.2.js (line 564)

2 个答案:

答案 0 :(得分:1)

以下是您的更新HTML。如果这有助于你,请告诉我。

注册表单HTML和脚本

<script type="text/javascript">
   $(document).ready(function() {
   $('#wait').hide();
   $('#wait').ajaxStart(function() {
      $(this).show();
   }).ajaxComplete(function() {
       $(this).hide();
   });

   $('#btn_register').click(function(){
       var parameters = $('#register_form').serialize();
      $('.error').empty();
      $.ajax({
        url: 'request.php',
        type: 'POST',
        data: parameters,
        dataType: 'json',
        success: function(response){
           if (response.success == 'success') {
               //do the things you need on success
           } else {
               if (response.error.email != '') {
                   $('#email_error').html(response.error.email);
               }
               if (response.error.password != '') {
                   $('#password_error').html(response.error.password);
               }
           } 
        },
        error: function(){
            console.log(arguments);
        }
     });

   });

});
</script>

<div class="content">
<div>
    <div class="title-bar" align="center"><h2 class="title">Registration Form</h2></div>

    <div class="inner-wrap pad">
        <div id="msg"></div>
        <div align="center">
        <form action="" method="post" id="register_form" enctype="multipart/form-data">
        <table width="60%" border="0" cellspacing="1" cellpadding="5" class="tb">
          <tr>
            <td width="30%" class="r"><label for="email">Email</label></td>
            <td width="70%">
                <input type="text" id="email" name="email" maxlength="50" value="" autofocus autocomplete="off" />
                <span class="error" id="password_error"></span>
            </td>
          </tr>
          <tr>
            <td class="r"><label for="password">Password</label></td>
            <td><input type="password" id="password" name="password" style="width:150px;" value="<?php echo isset($_POST['password']) ? $_POST['password'] : '' ?>" />
                    <span class="error" id="email_error"></span>
            </td>
          </tr>
          <tr>
            <td class="r"><label for="rpassword">Retype Password</label></td>
            <td><input type="password" id="rpassword" name="rpassword" style="width:150px;" value="<?php echo isset($_POST['rpassword']) ? $_POST['rpassword'] : '' ?>" /></td>
          </tr>
          <tr>
            <td class="r"><label for="fname">Full Name</label></td>
            <td><input type="text" id="fname" name="fname" maxlength="50" value="<?php echo isset($_POST['fname']) ? $_POST['fname'] : '' ?>" /></td>
          </tr>
          <tr>
            <td class="r"><label for="contact">Contact Number</label></td>
            <td><input type="text" id="contact" name="contact" maxlength="15" value="<?php echo isset($_POST['contact']) ? $_POST['contact'] : '' ?>" /></td>
          </tr>
          <tr>
            <td class="r"><label for="dob">Date of Birth</label></td>
            <td>
            <input type="text" id="dd" name="dd" style="width:24px;" maxlength="2" value="<?php echo isset($_POST['dd']) ? $_POST['dd'] : '' ?>" placeholder="dd" />&nbsp;/
            <input type="text" id="mm" name="mm" style="width:24px;" maxlength="2" value="<?php echo isset($_POST['mm']) ? $_POST['mm'] : '' ?>" placeholder="mm" />&nbsp;/
            <input type="text" id="yy" name="yy" style="width:40px;" maxlength="4" value="<?php echo isset($_POST['yy']) ? $_POST['yy'] : '' ?>" placeholder="yyyy" />
            </td>
          </tr>
          <tr>
            <td class="r"><label for="capcha"></label></td>
            <td>
            <div style="padding-bottom:3px;">
            <img id="captcha" src="inc/securimage/securimage_show.php" alt="CAPTCHA Image" />
            <a href="#" onclick="document.getElementById('captcha').src='inc/securimage/securimage_show.php?' + Math.random(); return false" class="capcha">Refresh</a>
            </div>
            <div><input type="text" name="ct_captcha" size="12" maxlength="8" id="capcha" style="width:100px;" /></div>
            </td>
          </tr>
          <tr>
            <td></td>
            <td><a href="javascript:void(0);" class="btn" id="btn_register">Proceed</a>&nbsp;<span id="wait"><img src="images/ajax-loader.gif" /></span></td>
          </tr>
        </table>
        </form>
        </div>
    </div>

</div>

此表单中的主要更改是我已经添加了<span class="error" id="password_error"></span><span class="error" id="email_error"></span>来保存错误内容,如果提交密码和电子邮件时发生错误。

单击“继续”时,将清空错误消息并将呼叫发送到服务器。服务器以json格式响应成功或错误消息。在响应中,我们将检查服务器是否响应成功消息或错误消息。这是使用response.success == 'success'完成的。如果响应成功,则表单已成功提交。

如果响应不成功,我们将检查服务器发送的错误类型,无论是电子邮件还是密码。我们将使用检查错误响应的类型 response.error.email != ''response.error.password != ''。这些将检查电子邮件和密码错误。如果发现错误,则使用我们已添加的ID将错误消息响应插入到相应的错误消息标记中。

我已经完成了电子邮件和密码。同样,您可以为所有字段执行操作。您只需将错误消息持有者添加到正确位置的html。

<强> Request.php

<?php

include('connectdb.php');
include('functions.php');

$email      = mysql_real_escape_string(strtolower(trim($_POST['email'])));
$password   = mysql_real_escape_string(trim($_POST['password']));

$message = array();

if(!check_email_address($email)){
    $message['error']['email']  = "Invalid Email Address";
}
if(empty($password) || strlen($password) < 0){
    $message['error']['password'] = "Invalid Password";
}

// if there are no errors return success callback
if(!isset($message['error'])){
    $message['success'] = "success";
}


echo json_encode($message);

?>

在request.php中我删除了$error变量并创建了一个新数组$message,并在多维数组中添加了错误消息,其中包含错误作为主键,字段名称为数组的二级密钥。

这样做的好处是我们可以在ajax回调中轻松解析带有字段名称的错误消息。

如果未找到任何错误消息,我们将成功消息添加到$message数组,并且成功。

希望你很清楚。如果这有助于您,请告诉我:))

答案 1 :(得分:0)

您还应该提供错误回调。服务器可能会抛出错误

$('#btn_register').click(function(){
    var parameters = $('#reg_form').serialize();

    $.ajax({
        url: 'request.php',
        type: 'POST',
        data: parameters,
        dataType: 'json',
        success: function(output_str){
            if(output_str == "error"){
                alert('Error: '+ output_str);
                //$('#msg').html(output_str);
            }else{
                alert(output_str);

            }
        },
        error:function(){
             console.log(arguments);
        }
    });

});