Reputation: 99
I am trying to debug a page that sends emails with attachments via ajax and when PHP kicks out an error, I get "Parse Error" because the error is not being sent back via JSON. Is there anyway to wrap up the PHP errors so I can alert them and see exactly what PHP errors are coming up?
What I am hoping to see in the js alert is the same thing you would see printed on the screen if this form was not submitted using ajax.
Upvotes: 0
Views: 3149
Reputation: 8357
function json_error($msg) {
header('HTTP/1.1 500 ' . $msg);
die(json_encode(array('error' => $msg)));
}
json_error('something bad happened');
This will trigger the error:
ajax callback on the JS side.
echo json_encode(array('anything' => 'really', 'any key' => 'any value'));
Will trigger the success:
callback.
Upvotes: 1
Reputation: 5377
Use HTTP status codes. Simple and clean.
On the client side: You can handle the HTTP states with the success and failure callbacks of the common JavaScript frameworks.
On the server side: Use exceptions and handle them with a catch
block. In the catch
block set the HTTP status code and echo the exception message. Or use the less fancy set_error_handler()
function and set the status code and error message in the callback function.
Upvotes: 5
Reputation: 7743
You'd use exception-handling, look here: http://www.php.net/manual/en/language.exceptions.php
Upvotes: 0
Reputation: 29975
Fatal errors usually can't be handled *.
Try improving your code and just don't make parse errors or other fatal errors. Handling warnings and notices is easy: http://php.net/manual/en/function.set-error-handler.php
*: It's possible but it takes a lot of effort.
Upvotes: 0