开发者

Function 'success' in Ajax/jQuery

I'm having problems displaying a value from the success开发者_开发百科 function of my Ajax call. My code is as follows.

$.ajax({
    type: "POST",
    url: "http://localhost/practical 8/checkuser.php",
    data: form_data,
    success: function(response)
    {
        if(response == 'success'){
            $("#errorUsername").html("<label class='error'>"+response+"</label>");
        }else if(response == 'fail'){
            $("#errorUsername").html("<label class='error'>"+response+"</label>");
        }
    }
});

My checkuser.php basically echos "succcess" or "fail".

My if and else if statements in my success function are not working. But doing

$.ajax({
    type: "POST",
    url: "http://localhost/practical 8/checkuser.php",
    data: form_data,
    success: function(response)
    {
            $("#errorUsername").html("<label class='error'>"+response+"</label>");
        }
    }
});

works perfectly. What am I doing wrong?


I won't critique the if branches resulting in the same code and will assume that is just there for testing purposes.

You'll want to check for extra white space being sent from the PHP script. That would explain why the javascript conditionals don't return true.

You can also trim the response with jQuery: response = jQuery.trim(response);


There could be a newline in the string. Try:

response = $.trim(response)

if(response == 'success'){
  $("#errorUsername").html("<label class='error'>"+response+"</label>");
}else if(response == 'fail'){
  $("#errorUsername").html("<label class='error'>"+response+"</label>");
}


The first argument for the success callback is the return data, followed by a text status argument. So try something like:

success: function (data, textStatus) {
    if (textStatus === "success" || textStatus === "fail") {
        // do something
    }
}

Note that a success response just means that the request succeeded, not necessarily that your code produced an error.


I agree with all the responses on this subject, however you should not use any spaces in your url's because this causes issues. Use _ instead of spaces if you want, but defiantly no spaces in your url's. Try all the recommendations and it should resolve your issues.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜