Reputation: 781
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?
Upvotes: 3
Views: 5339
Reputation: 55
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.
Upvotes: 0
Reputation: 5412
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.
Upvotes: 0
Reputation: 48887
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);
Upvotes: 5
Reputation: 70587
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>");
}
Upvotes: 1