How to Properly Catch a PHP error on Ajax call - php

I am retrieving javascript code from the server via the following ajax call
ajax (dojo):
dojo.xhrGet({
url : 'script.php',
handleAs : "javascript",
load : function(response){
/*Do Something*/
},
error : function(errorMessage) {
console.error(errorMessage);
}
});
script.php works fine, and, if the javascript code it returns is not valid code, the error handler will be invoked. However, the error message is incomplete, ie. it only shows the last function the error occurred in, not the entire chain of function calls. This is at times not very useful as I want to know where the error originated. Is there any way to output the entire trace?

Post the response of what you are returning.
I think you are better trying with a JSON response.

The reason I wasn't getting reliable error information is because I was using eval and I was expecting the same behavior I would observe having instead included those scripts. This question describes the differences and how eval runs the code whereas including those codes first inserts the code into the DOM then runs the code. The former is more efficient, but the latter is easier to debug.

I was getting the same error object on xhrPost for a _saveCustom, even though my response status was 200 (the 'handle:' is the same for GET and POST).
Actually handle: as 'json' will threw the error as well, but handle as 'text' worked and triggered the call to the load callback function.

Related

Capture PHP error body within jQuery AJAX

I have an AJAX build that functions like a CMD line box. It allows me to breakup and scrub 100,000+ line CSV files on servers where MySQL 'IMPORT from FILE' is disabled. That "scrub" process is different for every client. Therefore I have built this tool to allow me to include various PHP scripts
It works great except for error handling in 1 area: the PHP error level.
I want to log the error using JS, specifically console.log()
consider then the following JS
$.ajax({
type: 'POST',
dataType: 'text', //also tried json
url: PHP_SCRIPT, //for sake of referance
data: $.param(data), // param object values as POST values
cache: false,
error: function(error) {
console.log("fubar:" + JSON.stringify(error));
If I cause an error in PHP_SCRIPT (that is not handled using try/catch and output as JSON) then I get the following "ambiguous" reply
stringify:{"readyState":4,"responseText":"","status":500,"statusText":"error"}
Here is the problem: responseText is empty.
What is really happening in PHP_SCRIPT is this error:
Fatal error: Uncaught UnexpectedValueException: RecursiveDirectoryIterator::
Which I can of course see if I run the PHP script (and I know why its happening, my question is not about the RDI error). Consider it could be other errors as well: a failed include, a mistake in code, ect. But JS and jQuery AJAX do not seem to "capture" the body of the failed PHP script.
GOAL: I want to "capture" PHP errors and show them using console.log() (or even my makeshift CMD line box) so I do not have to cut up the PHP_SCRIPT's and debug each line separately. I do not understand why error.responseText does not capture the output.
Ideally - the PHP "Fatal error" above should have been captured as TEXT and output in the log.
Note: I have PDO try/catch handling for the DB queries where I can output a success.error object and handle it appropriately, catching the PDO exception and log it to the console. Alas, I see no useful way to handle other PHP errors (such as a failed include or other common PHP mistakes). If it matters- I am using WordPress Admin AJAX with nonce and die() and my scripts work great, but during dev of new scripts catching errors is annoying.
Question Summary:
Is there a way to catch all/any PHP errors that are not output as JSON and console.log them when $.ajax - error happens?
Is there some way to capture the 'body' of the PHP error and console.log it?
Thank you for your consideration in this matter
UPDATE---
Added video to clarify: http://www.screencast.com/t/ZyCeaMyAxBO
Something like this will capture all uncaught exceptions and output a message in JSON format.
set_exception_handler(function($e) {
$msg = "Error: ";
// maybe you want to treat some differently?
if ($e instanceof \PDOException) {
$msg = "Database error: ";
}
// you can access all properties of the exception to build a reply
$msg .= $e->getMessage();
header("Content-Type: text/json");
echo json_encode(["message" => $msg]);
});
You can't catch ALL error situations, basically because you'll have to write the error handler in PHP and some errors (like parse errors) cause that the script doesn't even compile and therefor cannot be executed at all.
But with set_error_handler() / set_exeception_handler() you can probably cover a good portion...

Why ajax receive different values than send from php controller

I have a problem with ajax response which is sent by php controller.
I have got these code in my php controller:
ajax_return_success is my function where i just json_encode my function argument.
When ajax is set to dataType: json it throws exceptions or receive NaN (depending on what data type is sent). I checked what is in $result and there is similar to $output. But when I change $result to $output in ajax_return_success everything runs smooth and good.
When ajax is set to dataType: text it shows that in response is:
{"STATUS":"OK","MESSAGE":["0","0","0","0"]}
But what it should looks like:
{"STATUS":"OK","MESSAGE":["2","1","1","6"]}
Have anybody encountered that problem ? What cause that difference in what i send and what i receive. I want to ensure that ajax_return_success works good because it is used in many places but there is something not ok.
P.S When I use Postman to send request everything is always fine. Problem is with standard ajax.
I have found the answer already! I have got errors notification shut off in my codeigniter and in one place in one function i have divided by 0. Unfortunately php dont give ... anything about it and continue, but ajax for some reason have strange behaviour. Today i have simmilar problem because for some, undefined reason ajax show error even that http status was 200.
And after debugging it shows off that dividing by 0 it is not a good idea ;)

Jquery post to php file works but can't return the data echoed in php

I can post the data using jquery (Checked with the mysql insert from that php file, it does insert, so i'm 100% sure that posting works), even though something is echoed in the php file, i can't seem to return that to the page with my data function (also checked if it echoes normally)... I know it should work, any ideas why it wouldn't?
$('#formbutton').click(function() {
var user = $('#nameinput').val();
$.post("usercount.php", {
username: user
}, function(data) {
alert("Data Loaded: " + data);
});
});
If the data is inserted, there should't be anything wrong with the request. My guess is that a fatal error occurs after the data is inserted, thus preventing the output. You should check your PHP logs for a clue.
You should also check the response code of the request in the Net panel in Firebug or similar tools. If the response fails, the callback function in $.post won't execute. Try using the $.ajax function instead, and provide both a success and an error callback.
Everything seems correct (or at least I can't see anything wrong now).
Use the network panel in firebug or chrome developer tools to inspect the request and the response of the ajax calls and see if they are correct (and also if the response comes with http status code 200). Also check the javascript console, put a breakpoint here or there and play with it (it's fun :D)

Has anyone ever successfully tracked down uncaught exception during ajax request?

How do ajax know whether it failed or succeeded if server side doesn't echo anything back?
$.ajax(error:..,success:..)
I met with this exception in my test:
uncaught exception: [Exception...
"Component returned failure code:
0x80040111 (NS_ERROR_NOT_AVAILABLE)
[nsIXMLHttpRequest.statusText]"
nsresult: "0x80040111
(NS_ERROR_NOT_AVAILABLE)" location:
"JS frame ::
http://localhost/script/tab.js ::
anonymous :: line 69" data: no]
The server side code is :
$id = process();
And for the purpose of testing,I have exit() in process();
Is that the reason for this exception?If so,why?
EDIT
I looked over to the line that cause exception,it's the error handling function of $.ajax()
error:function(XMLHttpRequest, textStatus, errorThrown){
alert(XMLHttpRequest.statusText);alert(textStatus);alert(errorThrown);
}
Anything wrong here?
The httprequest also returns a status such as 200 == ok, 404 == not found, 12152 == connection closed by server and so on..
Just read up on the status id's what they mean so you can look for them. you can also for debugging reasons just write out myhttprequest.status to the document and it shows what status it returned.
This depends on the status code the request returns. A successful request returns a status code in the range of 2xx, an error is in the range of 4xx of 5xx.
For more information see Wikipedia: List of HTTP status codes.
It would still get a response from the server, with the data part of it being empty. If it got no response at all, that would be an error.
http://docs.jquery.com/Ajax/jQuery.ajax#options
Give an option for success and error These functions will be called after the call is made.
There are four possible scenarios that you could get:
the server isn't there or refuses the connection (this is identifiable by the sockets library that the browser uses, which will report the connection failure)
the connection works and the server returns a non-success error code - this comes back in the header. Indeed, the request can succeed (200 code) even with an empty body, that's perfectly valid
the connection comes up but the server fails to respond - I'm not clear on the details of this, but i'd expect the JS to eventually time out because no response was received and return a failure based on that.
the connection comes up but the server responds incorrectly (e.g. no headers) - the JS implementation should return this as an error.
In any case, all the error scenarios are handled by the Javascript core's XMLHttpRequest implementation - jQuery just wraps it up with slightly tidier interface.
In your case (now you've provided more information) I would recommend that you use Firebug to see what the server response to your request is. That said, you shouldn't be getting an exception for anything inappropriate from the server, the JS should call the same error callback for all the above cases.
are you missing { } ?
$.ajax(error:..,success:..)
should be
$.ajax( { error: function( ){ } } );
if that's it, sorry dude, that would be annoying to have spent that much time on, haha
I fixed this by specifying a timeout in my ajax call. The ajax timeout was just giving up after X amount of time. Even though the page ended up returning data, the ajax object just gave up and bailed, but threw this error.

ajax request with prototype returns 200 success with blank html page (intermittent)

i have a page performing the following ajax request when a button is pressed.
normally i get a json object back and it works fine, i have noticed on intermittent requests (usually only the first request from that page), i get back a 200 success code with a blank page.
if i reload the html page, then press the button again it works fine straight afterwards.
by intermittent i mean i can't replicate the issue at will, but it is happening regularly enough that i need to do something about it
i am just wondering if it is most likely an ajax or in particular a prototype problem or a server side issue (i am using debian/apahce/php)
what can i try to track down the problem ?
new Ajax.Request( url,
{
method:'post',
parameters: $('TeamForm').serialize(true),
onSuccess: function(transport) {
// do stuff
},
onFailure: function(transport) {
// display error
}
});
This isn't a solution to your problem but a workaround -- in the meantime, you could detect if the response's responseJSON property is NULL, and if so, log the error and resubmit the request. That way at least the second request should go through. The easiest way to handle this might be to throw a custom object from your onSuccess handler allowing your onFailure handler to catch it and resubmit.
Based on the example you provided, the only source of concern I can see with the javascript is the $('TeamForm').serialize(true); statement. Are you sure that the TeamForm has well formed data, and your PHP backend is handling this appropriately?
Check your PHP code for any trailing whitespace. You should not end your PHP files with a closing tag.
e.g.
<?php
class Foo {
}
?> //There is a space after this closing tag!
Would result in the hidden space being sent to your browser. It is valid syntax (and recommended) to leave the closing tag off of a pure PHP file:
<?php
class Foo {
}
Also check your code for any echo's or print's that may send output to the browser. Also check your display_errors setting, as an error message could result in data being sent to the browser as well.
I'd put 99:1 odds on the problem being server-side.

Categories