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.
Related
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...
I have a JSON request which I'm posting to a HTTP URL.
Should this be treated as 400 where requestedResource field exists but "Roman" is an invalid value for this field?
[{requestedResource:"Roman"}]
Should this be treated as 400 where "blah" field doesn't exist at all?
[{blah:"Roman"}]
A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn't follow the rules.
In the case of a REST API with a JSON payload, 400's are typically, and correctly I would say, used to indicate that the JSON is invalid in some way according to the API specification for the service.
By that logic, both the scenarios you provided should be 400s.
Imagine instead this were XML rather than JSON. In both cases, the XML would never pass schema validation--either because of an undefined element or an improper element value. That would be a bad request. Same deal here.
From w3.org
10.4.1 400 Bad Request
The request could not be understood by the server due to malformed
syntax. The client SHOULD NOT repeat the request without
modifications.
Selecting a HTTP response code is quite an easy task and can be described by simple rules. The only tricky part which is often forgotten is paragraph 6.5 from RFC 7231:
Except when responding to a HEAD request, the server SHOULD send a
representation containing an explanation of the error situation,
and whether it is a temporary or permanent condition.
Rules are as following:
If request was successful, then return 2xx code (3xx for redirect). If there was an internal logic error on a server, then return 5xx. If there is anything wrong in client request, then return 4xx code.
Look through available response code from selected category. If one of them has a name which matches well to your situation, you can use it. Otherwise just fallback to x00 code (200, 400, 500). If you doubt, fallback to x00 code.
Return error description in response body. For 4xx codes it must contain enough information for client developer to understand the reason and fix the client. For 5xx because of security reasons no details must be revealed.
If client needs to distinguish different errors and have different reaction depending on it, define a machine readable and extendible error format and use it everywhere in your API. It is good practice to make that from very beginning.
Keep in mind that client developer may do strange things and try to parse strings which you return as human readable description. And by changing the strings you will break such badly written clients. So always provide machine readable description and try to avoid reporting additional information in text.
So in your case I'd returned 400 error and something like this if "Roman" is obtained from user input and client must have specific reaction:
{
"error_type" : "unsupported_resource",
"error_description" : "\"Roman\" is not supported"
}
or a more generic error, if such situation is a bad logic error in a client and is not expected, unless developer made something wrong:
{
"error_type" : "malformed_json",
"error_description" : "\"Roman\" is not supported for \"requestedResource\" field"
}
In neither case is the "syntax malformed". It's the semantics that are wrong. Hence, IMHO a 400 is inappropriate. Instead, it would be appropriate to return a 200 along with some kind of error object such as { "error": { "message": "Unknown request keyword" } } or whatever.
Consider the client processing path(s). An error in syntax (e.g. invalid JSON) is an error in the logic of the program, in other words a bug of some sort, and should be handled accordingly, in a way similar to a 403, say; in other words, something bad has gone wrong.
An error in a parameter value, on the other hand, is an error of semantics, perhaps due to say poorly validated user input. It is not an HTTP error (although I suppose it could be a 422). The processing path would be different.
For instance, in jQuery, I would prefer not to have to write a single error handler that deals with both things like 500 and some app-specific semantic error. Other frameworks, Ember for one, also treat HTTP errors like 400s and 500s identically as big fat failures, requiring the programmer to detect what's going on and branch depending on whether it's a "real" error or not.
Using 400 status codes for any other purpose than indicating that the request is malformed is just plain wrong.
If the request payload contains a byte-sequence that could not be parsed as application/json (if the server expects that dataformat), the appropriate status code is 415:
The server is refusing to service the request because the entity of
the request is in a format not supported by the requested resource for
the requested method.
If the request payload is syntactically correct but semantically incorrect, the non-standard 422 response code may be used, or the standard 403 status code:
The server understood the request, but is refusing to fulfill it.
Authorization will not help and the request SHOULD NOT be repeated.
Think about expectations.
As a client app, you expect to know if something goes wrong on the server side. If the server needs to throw an error when blah is missing or the requestedResource value is incorrect than a 400 error would be appropriate.
First check the URL it might be wrong, if it is correct then check the request body which you are sending, the possible cause is request that you are sending is missing right syntax.
To elaborate , check for special characters in the request string. If it is (special char) being used this is the root cause of this error.
try copying the request and analyze each and every tags data.
As a complementary, for those who might meet the same issue as mine, I'm using $.ajax to post form data to server and I also got the 400 error at first.
Assume I have a javascript variable,
var formData = {
"name":"Gearon",
"hobby":"Be different"
};
Do not use variable formData directly as the value of key data like below:
$.ajax({
type: "post",
dataType: "json",
url: "http://localhost/user/add",
contentType: "application/json",
data: formData,
success: function(data, textStatus){
alert("Data: " + data + "\nStatus: " + status);
}
});
Instead, use JSON.stringify to encapsulate the formData as below:
$.ajax({
type: "post",
dataType: "json",
url: "http://localhost/user/add",
contentType: "application/json",
data: JSON.stringify(formData),
success: function(data, textStatus){
alert("Data: " + data + "\nStatus: " + status);
}
});
Anyway, as others have illustrated, the error is because the server could not recognize the request cause malformed syntax, I'm just raising a instance at practice. Hope it would be helpful to someone.
This reminds me of a common dialog with others, "I understand - I just don't Agree"
400 means the server didn't understand
200 means the server understood exactly and fully processed the request.
When a server returns 200 it is saying, "I understood what you are asking for, I processed it without unexpected errors, and here is my proper response"
200 means you can trust the answer sent in the response. Maybe the answer is "Romans aren't allowed" - but still, it is a proper answer, generated without any unexpected problems.
200 doesn't express any information about Expected errors or Handled Exceptions - because that is not part of the Message Transport process. These are status codes about HTTP, the Status of the Transport itself.
I believe Blurring the line between "Transport/Communication" VS "Processing" should be avoided.
For those who prefer HTTP Codes to indicate problem in processing (the "I don't agree" part) it seems 409 Conflict is the most applicable to "Romans not allowed"
RFC 7231 409 Conflict
Conflict pretty much means "lack of agreement" right?
No matter what you choose for HTTP response code, it seems everyone agrees your response should explain Why it failed, and what to do to resolve it. In the case of Roman, maybe return a list of acceptable values for the field?
In my case it meant that the data I was providing in json was not compatibile with required data for db, for example email address was already added into db and then it throws code 400
I have been looking around the web (obviously in wrong places) to find what is the success and failure criteria for ajax(jquery post) purposes.
For example, let's say I am using ajax to post to a php script. The script can return:
exit 0
exit 1
jason array
return
etc...
When would those return values be translated into success and when into failure?
As you may already know $.ajax() supports beforeSend, success, error and complete callbacks.
So what should my script send in case of success and in case of failure for the appropriate callback to be triggered.
Ben is right, but I'll expand a little.
jQuery determines success or failure based on the HTTP response code of the page being called. Note that this is not the same as the content in the response that is sent back.
As an example, let's say that you have your PHP script located at http://url.com/script.php
When a user hits that site, they are going to get a response from the server. That response could be a JSON object, it could be an HTML page, or it could be an empty response. In all of these cases, the response code would likely be 200. A 200 response code means that the server understood the request, accepted it, and sent something back.
Now let's say that a user tries to hit http://url.com/notascript.php
The server doesn't know what to do with that (assuming that notascript.php doesn't actually exist). It fails the request, and sends back a response -- probably with the response code 404 (or something else in the 4xx range).
So if you know the actual URL, then how does jQuery's error handler ever get called?
Well, let's say that your AJAX call is trying to load a blog post, and tries to make a call like this: http://url.com/post?id=5. If your PHP script determines that there is no blog entry with an ID of 5, then you probably shouldn't send back a successful response. Rather, a 4xx response would be more appropriate. And PHP has a built-in function for that:
<?php
http_response_code(404);
?>
Now, the response will be read by jQuery as a failure, and the error handler will be called.
Further reading:
http_response_code() function
RFC2616, which defines HTTP response codes
REST
I believe it's based on header codes (ie, 200 - success). You can send your own special errors back though e.g. How to receive error in jQuery AJAX response?
You shouldn't make Ajax error if you have a problem with the code in the page being requested. As far as Ajax is concerned, so long as the page physically is successfully requested, it has performed properly. Any errors within the page being requested are not a fault of Ajax, so should be handled by your code after a successful load of that page. Using custom headers as in the link above will make it easier for you to do that.
Ajax requests page --> Page loads & no errors --> page request successful --> You Perform result error checking
vs
Ajax requests page --> Page loads & has errors --> page request successful --> You Perform result error checking
As you can see, it doesn't matter if the page being requested has errors, it's not an Ajax fault, so shouldn't be treated as one.
You can select one pattern that always printed for success, other cases like ajax failure can be known via AJAX itself (HTTP response code): for example:
You always print: yes for success and if correct result found
You always print: no for success and if incorrect result found
If none of above returned then its ajax failure or if the script prints another word then you need to check your 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.
I build JQuery/JS/PHP/mySQL app with DB records management and need to provide reliable & complete feedback to the user on AJAX calls, modifying back end DB records. The problem IMHO is $.ajax success: and error: functions indicate just AJAX transport layer success and not the whole process. What if DB modification fail? How can one provide the complete feedback to the user?
I ended up with
$.ajax({
url: "/action/delete",
data: "rowid="+rowid,
complete: function(xmlHttp) {
if ( xmlHttp.responseText ) alert('Success - back end returned "success"');
else alert('failure - back end returned NULL')
}
});
and PHP response:
$success = deleteRecord( $_GET(rowid) );
if($success) {
print 'success';
} else {
print NULL;
}
exit();
The idea is simple - if I manage to get positive feedback from the back end, then the whole operation succeeded, if not - user don't care where problem occurred.
Thank you in advance, your feedback is highly appreciated.
If you respond to the request with some json data instead of just some new html to insert into the DOM, you can place whatever kinds of error codes and messages you like with the data. For example, if your response was something like...
{
errorstate: 0,
errormsg: "All systems are go",
displaytext: "stuff I want to display when all goes well"
}
Your javascript code can examine this data and do whatever it feels it needs to. It also allows you to push more of the error handling into your server script which can often be simpler.
Try http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback
One possible solution would be to use the HTTP response code to signal a failure, like 200 OK, everything's ok, and 500 Internal Server Error on error, which you can simply check when you reach state 4.
In PHP I believe this is done through header("HTTP/1.0 200 Ok") before any other data is sent. If you're afraid data will be sent by mistake before you can evaluate the correct header to set you can turn on output buffering.
How you wish to present the data is of course up to you, you could for example on 500 just have document.getElementById("myerrorbox").innerHTML = xmlHttp.responseText, or similar, and render a partial html-document in your php-program.
I send status messages back to the client. Along with the error flag. And then my JavaScript code displays the message it got from the server, and colours the message according to the error flag.
I find that to be quite efficient.