PHP errors and AJAX
handgestrickt is developing AJAX-applications with PHP. a common problem is, that you never know whether your PHP-scripts really do what you want and also retrieve the information you send. sometimes errors are thrown and you do not even know it. you could output the responseText of your request all the time, but you always need to uncomment it later. for debugging of big engines it is rather time consuming. this is why we developed an easy way to catch those error messages.
var foo = {
handle_AJAX_result: function(obj) {
var response = obj.responseText;
if(response && response.search(/>(?:parse|fatal)\s+error<|>warning</i) != -1) {
response = response.replace(/<[^>]+>|foo\.[^\n]+/g,'');
response = response.replace(/\s+/g," ");
alert("PHP errors have been thrown:\n\n"+response);
}
else if(response && response.search(/!debug!/i) != -1) alert("debug information:\n\n"+response);
},
example_function: function() {
new Ajax.Request('some_script.php',
{
method: 'post',
parameters: {
parameter1: 'something',
parameter2: 'whatever',
parameter3: 'another_nonsense'
},
asynchronous: true,
onComplete: function(obj) {
foo.handle_AJAX_result(obj);
foo.do_something();
}
}
);
},
do_something: function() {
alert('i do something!');
}
}
the way it works is very simple: everytime the response contains some PHP errors, fatals or warnings, the result is shown on the screen. this is good for debugging. additionally if you intentionally want it to be shown, you just echo() the string "!debug!" somewhere in your PHP code. example:
<?php
echo ' /*';
echo '!debug!';
print_r($some_content);
echo '*/ ';
?>
we output the result of our print_r() in comments. so it does not disturb the execution of our JavaScript or JSON-output. the magic string "!debug!" tells our JavaScript function that we want to see the output on the screen.

