Greetings,
I was trying to discover a proper way to send captured errors or business logic exceptions to the client in an Ajax-PHP system. In my case, the browser needs to react differently depending on whether a request was successful or not. However in all the examples I've found, only a simple string is reported back to the browser in both cases. Eg:
if (something worked)
echo "Success!";
else
echo "ERROR: that failed";
So when the browser gets back the Ajax response, the only way to know if an error occurred would be to parse the string (looking for 'error' perhaps). This seems clunky.
Is there a better/proper way to send back the Ajax response & notify the browser of an error?
Thank you.
You could send back an HTTP status code of 500 (Internal server error) , and then include the error message in the body. Your client AJAX library should then handle it as an error (and call an appropriate callback etc.) without you having to look for strings in the response.
I generally send back a JSON response like this:
$response = array('status' => 'error', 'message' => 'an unknown error occured');
if( some_process() ) {
$response['status'] = 'success';
$response['message'] = 'Everything went better than expected.';
} else {
$response['message'] = "Couldn't reticulate splines.";
}
die( json_encode($response) );
So, I can check the status of response.status
in my JavaScript and look for a value of "sucess" or "error" and display response.message
appropriately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With