使用jquery ajax提交表单并处理响应

时间:2012-09-03 12:20:45

标签: php ajax jquery

在下面的代码中,我在Firebug中遇到'TypeError:response is null'。我尝试了许多组合和试图获得响应的方法但没有成功。请看看,告诉我我做错了什么。谢谢!

$("a.logmein").colorbox({ width:"540", height:"420", href:function(){ return this.href + " #login"; }, onComplete: function(){
     $("#formLoginUser").submit(function(){
         $.ajax({
          data: $(this).serialize(),
          type: "POST",
          url: $(this).attr('action'),

          success: function(response) {
            if(response.status == 'fail'){
              $("#notifications").removeClass().addClass('ajaxerror').html(response.message).show();
            } else {
              $("#notifications").removeClass().addClass('ajaxsuccess').html(response.message).show();
            }
            console.log(response);

          },
          error: function (xhr, textStatus, errorThrown) {
            $("#notifications").addClass('ajaxsuccess').html(xhr.responseText).show();
          }
        });
return false;
    });
 }});

ajax.php:

header("Content-Type:application/json"); 

    switch($_REQUEST['action']){
        case('formLoginUser'):      $afm = $_POST['afm'];
                                    $password = $_POST['password'];

                                    $query_finduser = sprintf("SELECT * FROM clients WHERE clientafm=%s and clientcode=%s and expires>%s",
                                                                   GetSQLValueString($afm, "text"),
                                                                   GetSQLValueString($password, "int"),
                                                                   GetSQLValueString(strtotime('now'), "int"));
                                    $finduser = mysql_query($query_finduser, $connection) or die(mysql_error());
                                    $row_finduser = mysql_fetch_assoc($finduser);
                                    $totalRows_finduser = mysql_num_rows($finduser); 

                                    if($totalRows_finduser==0) {
                                        echo json_encode(array("status"=>"fail", "message"=>"Login failed. Please retry"));
                                    } else {    

                                        echo json_encode(array("status"=>"success", "message"=>"Login successful!"));
                                    } 
                                    break;

    default:                    break;

}//switch end

1 个答案:

答案 0 :(得分:1)

到期jQuery docs success回调函数有3个输入参数:success(data, textStatus, jqXHR)。剩下的参数怎么样?试着检查一下。也许错误在那里。