Reputation: 307
I'm making an ajax call in jquery to a php script. But what does the php script need to return for the success/error handler in ajax to fire. So here's the ajax:
$.ajax({
data: $this.serialize(),
type: "POST",
url: "/Scripts/script.php",
success: function() {
alert("script was successful");
},
error: function() {
alert("script was unsuccessful");
}
});
So there are a few things the php script can return such as:
return 0, 1
return true, false
return "true", "false"
echo "true", "false
Which one fires the ajax success/error calls?
Upvotes: 3
Views: 7011
Reputation: 1039438
As long as the server side script sends HTTP status code 200 it will always fire the success
callback. The response doesn't matter at all. Only the status code. In all examples you have shown you are sending HTTP status code 200 => the success callback will always trigger.
You could force the status code to something different than 200 using the http_response_code
function.
As an alternative you could have your PHP script return some information and then inside the success function test the value that was returned by your script to know whether some server side processing has failed or not:
$.ajax({
data: $this.serialize(),
type: "POST",
url: "/Scripts/script.php",
success: function(result) {
if (result == 'true') {
alert("script was successful");
} else {
alert("script was unsuccessful");
}
},
error: function() {
alert("something very bad went wrong => there's a bug in the script");
}
});
Now your script could echo true
or false
.
If you want to send complex objects you could send them as JSON using the json_encode
function and setting the HTTP Content-Type header to application/json
using the header
function.
Upvotes: 11
Reputation: 3917
Succes executes on a request completed with no errors on XMLHTTPRequest
, doesn't matter what you are returning as a result. There is another complete
callback, which executes on your AJAX script complete, doen't matter if you have XMLHTTPRequest errors.
Upvotes: 0