Handling a fatal error in PHP from an AJAX call
Quite simply, I want my javascript to be able to react to a fatal 500 error caused by PHP, appropriately to the error.
My goal is 开发者_开发百科simply to collect the fatal error message that the script produced, so I can show it on the client side.
Is this in any way possible?
EDIT: cleaned up the question, in case it gets, by chance, it gets searched.
Processing Fatal Errors in PHP:
register_shutdown_function("foo");
function foo() {
$e = error_get_last();
if($e & (E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR)) //all fatal errors
[handle the error. I turn the error into a json encoded object that is parsed by JS]
}
By checking for all fatal errors, you won't trigger the handle for notices or warnings that happened earlier, but didn't stop execution of the script. Hopefully you already handle those.
Side note:
Handling fatal errors using jQuery:
$(document).ajaxError( function(e, xhr, settings, exception) {
[handle 500 error. xhr.responseText will contain the printed text.]
});
$.post( [...] );
See http://api.jquery.com/ajaxError/ for more details.
Final Note: display errors should be off if you wish to parse JSON, or text will appear before the JSON encoded object.
Check out the .status
for an AJAX request.
ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 500)
{
//do something
}
}
ajaxRequest.open("GET","path/file.php?var=variable");
ajaxRequest.send();
^in a nutshell
I provided this code to another user, that would be your solution here. Just use the Jquery 1.5 XHR object to receive error states and if it is an error state, to something with it from your javascript code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
$(function(){
alert('getting page');
jqXHR = $.get(
'index.php',
function(data){
alert(data);
}
)
.success(function(){ alert('second success'); })
.error(function(){ alert('error'); })
.complete(function(){ alert('complete'); });
});
</script>
精彩评论