关于AJAX,FORM和PHP

时间:2014-07-14 11:27:00

标签: javascript php jquery ajax

我的ajax代码看起来像检查注册表单用户名,电子邮件等...

jQuery(document).ready(function($) {
$("#formform").on('change', 'input',function(event){
    var $form = $(this);
    var $inputs = $form.find("input, select, button, textarea");
    var serializedData = $form.serialize();
    $inputs.prop("disabled", true);

    request = $.ajax({
        url: "/registration_check.php",
        type: "post",
        data: {formData:serializedData},
        datetype: "JSON"
    });
    request.done(function (response, textStatus, jqXHR){
        console.log(response);
    });
    request.fail(function (jqXHR, textStatus, errorThrown){
        console.log("error");
    });
    request.always(function () {
        $inputs.prop("disabled", false);
    });
    event.preventDefault();
});
});

我的PHP看起来像这样:

$get_form_data=$_POST["formData"];
parse_str($get_form_data,$form_data);

if(isset($form_data["username"])){
    if(strlen($form_data["username"])<5){
        echo "Username must be at least 5 character";
    }else{
        if(ValidUserName($form_data["username"])){
            if($checkUser->checkUserName(char_encoder($form_data["username"]))==true){
                echo "Sorry this UserName Already Exist";
            }else{
                echo "UserName Available";
            };
        }else{
            echo "Invalid Username";
        }

    }

}

现在当无效用户名来自AJAX作为响应时,如何禁用表单?

我虽然应该使用return false ..但不知道如何处理响应?

2 个答案:

答案 0 :(得分:1)

尝试以下格式,您可以处理成功事件中的响应:

var $form = $(this);
var serializedData = $form.serialize();
$.ajax({
    type: "POST",
    url: "/registration_check.php",
    data: {
        formData:serializedData
    },
    beforeSend: function () {
        //do stuff like loading process until you get the response
    },
    success: function (resp) {
        var obj = jQuery.parseJSON(resp);
        //console.log(obj); // this will display response in console.
        //do stuff here

    },
    error: function(e){
        alert("Error in ajax call: "+e);
    } 

}); // complete AJAX  

PHP代码:

$array = array();
if (isset($form_data["username"])) {
    if (strlen($form_data["username"]) < 5) {
        $array['success'] = false;
        $array['message'] = "Username must be at least 5 character";
    } else {
        if (ValidUserName($form_data["username"])) {
            if ($checkUser->checkUserName(char_encoder($form_data["username"])) == true) {
                $array['success'] = false;
                $array['message'] = "Sorry this UserName Already Exist";
            } else {
                $array['success'] = true;
                $array['message'] = "UserName Available";
            }
        } else {
            $array['success'] = false;
            $array['message'] = "Invalid Username";
        }
    }
    echo json_encode($array);
}  

答案 1 :(得分:0)

在表单提交事件上进行ajax调用,如果ajax返回任何错误,则调用event.preventDefault();。 希望这有帮助:)