I've searched the questions on here, but I don't have a good understanding of how to use the error handling in jQuery's AJAX (im a noob, so it just really doesn't make sense.)
Can anybody describe this to a beginner? I'm currently posting information to a PHP script via AJAX, but want to allow jQuery to recognize if the returned data from the script is an error or success.
Thanks!
Dave
The error return from the ajax call is returning the results from a page load that was not successful. It may be that your php page returns a valid page, but with results that are not what you want. This is handled withing the success return. Hopefully the following code snippit will help illustrate...
$.ajax({
type: "POST",
url: "login.php",
data: "action=login&user=" + user + "&pass=" + pass,
success: function(xhr){
if ((xhr == "Invalid Login")
|| (xhr == "Invalid charaters in username.")
|| (xhr == "Missing username or password.")
|| (xhr == "Unknown Error")) {
$("#loginMessageContent").html(xhr);
}
else {
simplemodalClose (dialog);
}
},
error: function(xhr) {
alert ("Oopsie: " + xhr.statusText);
}
});
The jQuery AJAX error handling is implemented to handle if the HTTP Request has an error not if your script is returning "error" or "success". If the server throws an error (404 Not Found or 500 Server Error as an example) then it will trigger the error functions of jQuery. It can be handled a few ways, but one nice way is to show a div letting the user know there was an error.
HTML
<div id="error" style="display: none">There was an error processing your last request</div>
jQuery
$(function(){
$("#error").ajaxError(function(){
var $error = $(this);
$error.slideDown(500, function(){
window.setTimeout(function(){
$error.slideUp(500);
}, 2000);
});
});
});
If an error occurs, none of your "success" methods will fire, and that div will slide down, wait 2 seconds, then slide back up.
Testing your script for errors
As I mentioned what you described sounds like your server script is sending "error" or "success" or something similar back to the client.
If you are using a $.post, for example, your error handling code might look like this:
$.post('/your/url', { save_me: true }, function( data ){
if(data == "error"){
// handle error
} else {
// handle success
}
}
This is only 1 approach. I am building an application that returns all of its data in JSON. If there is an error then the JSON message is changed to reflect this. Every return object has a "status" of
either "success" or "error". If it is an error then there is an "error_message" part of the JSON that
describes the error.
I hope that helps.
Even though it's not your problem, I'll post here since it's related.
With the recent JQuery v1.4 release, JSON responses are now validated. It broke my app because I returned:
{success:true}
and now it's required to be
{"success":true} // HAS to be double quotes, single won't do it
If incorrect, it calls the error handler. Easy fix but took a bit to figure out.
Related
Even though the below PHP code exits with an error, the success callback in the AJAX code is still being triggered. Why is that?
JavaScript code :
$.ajax({
type: "POST",
url: xxxx,
data: {info:data},
success: function(result){
//code here
},
error:function(msg)
{
alert('add data error,please add again');
}
});
php code:
if(is_wrong) //data is error
{
exit("the data is not right,please add again");
}
There are various ways to handle error or success, when communicating between the client and server.
1. with HTTP status code
One of the $.ajax() callbacks (success and error) will be called, depending on the HTTP status code returned by the server. The "normal" success code is 200 OK. When you send output with a PHP script, if everything goes well, your generated content will be sent with code 200.
This is the case when you call exit() here. From the point of view of your client-side JavaScript code, since it received status code 200 OK, it will call the success callback. If you want the error callback to execute, you have to send custom headers in your PHP code, before sending any other output.
You can achieve this with the header function. For example, the following code can be used to generate a "404 Not Found" status:
header("HTTP/1.0 404 Not Found");
Here you would need to find another HTTP code that corresponds to your code better. I don't think this approach is the best solution, because HTTP status codes are meant to be server status codes, i.e. not meant for reflecting application error codes.
2. with your own conventions
The other way would be to handle the application error codes would be to handle everything from the success() handler. You don't set error codes from your PHP, but establish a convention to tell when you have an application error or a normal case. You would still keep the error() callback, so that you can handle various HTTP errors (i.e. if your connection to the server is broken).
For example, if you send your data from the server to the client as JSON, you might send from your php:
if(is_right) //data is ok
{
$response = array(
'data' => $someData, // any data you might want to send back to the client
);
}
if(is_wrong) //data is error
{
$response = array(
'error' => "the data is not right,please add again"
);
}
// Called in both cases
exit(json_encode($response));
In your client-side code, you would have:
...,
success: function(result) {
if(data.error !== undefined) {
// do something if your server sent an error
console.log(data.error);
}
else {
var data = result.data;
// do something with the data
}
},
...
I am using the jQuery UI autocomplete feature for some <input type='text'> boxes where it should return some selections depending on the input. This is working fine but now I need to add a check if the user even is allowed to do this lookup and if not, the user should be alerted.
This is my current code (or some of it at least):
$(this).autocomplete({
source: function(request,response) {
$.ajax({
url: 'search.json',
data: { field: thisName,
search: request.term }
}).done(function(data) {
response(data);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.dir(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
},
minLength: 1,
...[CUT]...
If I inside my search.json only has this http_response_code(403); I will receive this in the console (I hope the picture is readable):
So my question is - how can I report back an error to the autocomplete script so it acts correctly? For example it could alert the user in some way.
Currently I want to report back with a 403 Forbidden code but there could be other errors too - e.g. the user session could expire or alike. It doesn't necessarily needs to be a HTTP response code but this is what I see as the most correct to use in this scenario?
Please see the JSFiddle demo for my code.
I am using jQuery 1.11.0 and jQuery-UI 1.10.4 together with PHP 5.4 on an IIS 7.5. The IIS will pass .json files as normal PHP files - just to clarify if important.
Using AjaxSetup seems to be an option:
$.ajaxSetup({
error: function (x, status, error) {
if (x.status == 403) {
alert("Sorry, your session has expired. Please login again to continue");
window.location.href ="/Account/Login";
}
else {
alert("An error occurred: " + status + "nError: " + error);
}
}
});
Source: http://cypressnorth.com/programming/global-ajax-error-handling-with-jquery/
Since $.ajax() also supports the error method, it might also work for $.ajax() itself.
I actually found out that this was caused by me having my own error pages defined in the IIS. When changing the errorcode 403 to someting else (e.g. 999) I will get the 403 error to my Ajax script:
I have answered this myself in case others are having a similar problem and not being aware that their selfdefined HTML error messages/pages will give a HTTP response code of 200 in the Ajax.
I have a jQuery function, which is using AJAX to send the necessary information to run the respective script properly:
$("#changeUseridForm").submit(function(){
$.ajax({
type: "GET",
url: "API/root/users/changeUsername.php",
data: {
newUsername: ("#newUserid", this).val(),
password: ("#retypePass", this).val(),
xml: 1,
},
dataType: 'xml',
success: function(xml){
if($(xml).find("success").length > 0){
alert("Username changed successfully!");
$("#changeUserid").hide();
$("#BackToMainMenu").hide();
$("#MainPage").show();
$("#AddLinkButton").show();
$("#ChangeUserOptions").show();
$("#ChangeUserDataButton").show();
$("#ShowPosts").show();
}
else if($(xml).find("error").length > 0){
alert("You have to fill all the fields!");
}
}
});
return false;
});
I have several functions like this one, running perfectly; this one isn't. I verified all my variables and scripts. They're spelled correctly. It doesn't reach to the script referenced. I think the AJAX code might have a problem, but I can't detect which error is. I tried to search it on my browser's web inspector, but I can't figure it out since the page is reloading for some reason that I don't know why. (Because this function doesn't have window.location.reload() in it anywhere.)
try to set up a proxy or use firefox plugin to catch the get request(you can also use wireshark)
then you can see if there's a request to this page API/root/users/changeUsername.php
it is possible that this page API/root/users/changeUsername.php returns 302 redirect,
Check the http response of the GET Request and post it please
Look in the docs on .ajax(), you can specify an error handler function that gets details about what went wrong. That would be the first step.
You can also use Firebug's or Chrome's "Net" tab to monitor the request, and see what was returned.
You can detect (debug) a lot of errors using firebug. In this case you can use the net tab and check persists to see what request is causing reloaded page.
i am facing a problem of redirecting the site while in an ajax call..
here is what i wanna do :
make an ajax call to the server.
it goes to a certain process, if an error occurs, i should send to the error page, else resume.
now the problem is when in the server side, if i use :
header('Location: error.php');
It doesnt redirect the page, infact it just brings the data of that page (the whole html) to the javascript success function.
The problem is that i have made a generic library both on the javascript side (to call the ajax) and on the server side.
i need to redirect the page through the server side. i tried adding a js code for
window.location='error.php';
but didnt get any success
Why not return an error that the Ajax query can understand instead?
if ($error)
{ header("HTTP/1.1 500 Internal Server Error");
echo "A database error has occurred. etc.etc.";
die();
}
this will trigger the Ajax request's error callback (if in jQuery). The echoed text will be in the response body.
You can also look for a more fitting status code depending on the situation.
I think you should have an error handler in your ajax lib. In the server you send back either the correct html or an error code in the header plus the URL to redirect to in the body. In the ajax lib the error code in the header will trigger the error handler. In the error handler you can redirect using window.location = 'page_returned_by_server'
If an error occurs, simply echo the url of the errorpage. For example, using JSON:
Server-side:
echo '{error: "error.php"}';
Client-side:
var xhr = $.ajax({ url: "example.php" })
.success(function() {
var obj = JSON.parse(xhr.responseText)
if obj.error {
window.location = obj.error;
}
})
Have you considered using the $.ajaxError() global AJAX event?
$(document).ajaxError(function(event, jqxhr, settings, exception) {
alert('An AJAX error occurred in script: ' + settings.url);
console.log(event, jqxhr, settings, exception);
});
In your main JS lib could do the trick and you can add any type of redirect you like.
Here's the official jQuery documentation..
Hi guys I've noticed that at times exceptions do get thrown on server sided code - however when it comes to ajax requests how do I implement it such that I'm able to inform the user that an exception has been thrown and something has gone wrong? I'm using Php on the back end here.
It depends on what does the AJAX method return. If it is plain HTML, you could output an error message instead, which will be presented to the user.
If it is JSON, then add some fields to the structure, which can hold an error message or error code, so you can handle it when you retrieve the response client side.
Your ajax request can respond with a server code of 500 alerting the AJAX caller that something went horribly wrong. Most libraries implement an onFailure callback that will be triggered in this event.
I don't know if you use jQuery or not. My answer is given assuming you use jQuery, but you can apply the same concept to another JavaScript framework (or none). In this way, the users would actually be looking at the stack trace instead of a generic error message (which is uselss anyway):
$.ajax({
url: '/some_url',
type: 'post', //or get
data: ...,
success: function() { /* handle success */ },
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#error_dlg').dialog('open').trigger('initDlg', [XMLHttpRequest]);
}
});
$('#error_dlg').dialog({
autoOpen: false,
width: 550,
height: 400,
modal: true,
buttons: {
'Close': function() {
$(this).dialog('close');
}
},
open: function(event, ui) {
}
}).bind('initDlg', function(e, XMLHttpRequest) {
$('#error_stack_trace').append($('<div>').html(XMLHttpRequest.responseText));
});
Something I ran into recently that might be helpful is this:
http://php.net/manual/en/function.set-error-handler.php
Basically, if PHP runs into an error, it will use your handler, which you can design to work with an asynchronous request or a synchronous request.
However, it seems that you are also throwing exceptions within your code. From a cursory glance, you can create a custom Exception handling class as well.
http://www.w3schools.com/php/php_exception.asp
Once again, you can design it to work with asynchronous or synchronous requests. In your Javascript, if you are using JSON as a response, you can simply set an error flag that will alert your code of an exception/error and it will respond appropriately. If you're using straight HTML as a response, you might have to send a 500 error (or one of the other variants, I'm not well versed in the 500 codes) so that you can use the onFailure or failure function handlers as others have mentioned.