I was recently trying to debug some Ajax PHP code. I was logging but it was cumbersome trying to look at both the php log file and Javascript logging in Firebug so I started going some searching. I found post from Mika Tuupola about Debugging PHP With Firebug, so I took his advice and moved to the PEAR:Log package with a Firebug handler.
But I still had a problem since I was debugging Ajax requests. The way the system works is it tacks on Javascript code to your page in a script tag that will be run when the page loads. This is fine for a standard page but for an Ajax request the result isn’t run. Basically the response would look something like this.
<results>
<result>34</result>
<result>5</result>
</results>
<script type="text/javascript">
console.log("there are 2 results");
</script>
So all I did was write a function to strip out that Javascript code and execute it. The code is here
exfer.extractDebugMessage = function (s) {
var beginIndex = s.indexOf("<script");
if (beginIndex != -1) {
var str = s.substring(beginIndex); // extract the script tag at the end of the response
str = str.replace(/\n/g, "[N]"); // converts carriage returns into "[N]" so the regular expression can work without the "m" option
var result = str.match(new RegExp("<script.*>(.*)<\/" + "script>")); // get the code from the tag
if (result && result[1]) {
str = result[1].replace(/\[N\]/g, "\n"); // put the CRs back in
if (typeof console != "undefined") { // if console is available execute the code
eval(str);
}
}
s = s.substring(0, beginIndex);
}
return (s);
}
Then the code is called with the XMLHttpRequest responseText.
var realResponseText = exfer.extractDebugMessage(xhr.responseText);
Which pulls out the debug message and executes it, then returns what is left over to be passed along.
There are potential holes in the code of course. For example someone might have the string “<script” in their Ajax response but since it’s a debugging tool I’m not too worried about it. One quick note, since the code looks for the existence of console instead of Firebug it should also work with Firebug Lite although I haven’t yet tested it.



Post a Comment