I would like to catch the error and show the appropriate message if the Ajax request fails.
My code is like the following, but I could not manage to catch the failing Ajax request.
function getAjaxData(id)
{
$.post("status.ajax.php", {deviceId : id}, function(data){
var tab1;
if (data.length>0) {
tab1 = data;
}
else {
tab1 = "Error in Ajax";
}
return tab1;
});
}
I found out that, «Error in Ajax» is never executed when the Ajax request failed.
How do I handle the Ajax error and show the appropriate message if it fails?
asked May 14, 2010 at 12:07
Since jQuery 1.5 you can use the deferred objects mechanism:
$.post('some.php', {name: 'John'})
.done(function(msg){ })
.fail(function(xhr, status, error) {
// error handling
});
Another way is using .ajax:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
answered May 14, 2010 at 12:11
choisechoise
24.7k19 gold badges75 silver badges131 bronze badges
4
jQuery 1.5 added deferred objects that handle this nicely. Simply call $.post and attach any handlers you’d like after the call. Deferred objects even allow you to attach multiple success and error handlers.
Example:
$.post('status.ajax.php', {deviceId: id})
.done( function(msg) { ... } )
.fail( function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
});
Prior to jQuery 1.8, the function done was called success and fail was called error.
answered Aug 24, 2012 at 21:17
Michael VenableMichael Venable
5,0113 gold badges23 silver badges20 bronze badges
5
$.ajax({
type: 'POST',
url: 'status.ajax.php',
data: {
deviceId: id
},
success: function(data){
// your code from above
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
answered May 14, 2010 at 12:12
jAndyjAndy
232k57 gold badges305 silver badges359 bronze badges
0
$.post('someUri', { },
function(data){ doSomeStuff })
.fail(function(error) { alert(error.responseJSON) });
answered Feb 28, 2014 at 21:39
marknerymarknery
1,5333 gold badges19 silver badges27 bronze badges
1
A simple way is to implement ajaxError:
Whenever an Ajax request completes
with an error, jQuery triggers the
ajaxError event. Any and all handlers
that have been registered with the
.ajaxError() method are executed at
this time.
For example:
$('.log').ajaxError(function() {
$(this).text('Triggered ajaxError handler.');
});
I would suggest reading the ajaxError documentation. It does more than the simple use-case demonstrated above — mainly its callback accepts a number of parameters:
$('.log').ajaxError(function(e, xhr, settings, exception) {
if (settings.url == 'ajax/missing.html') {
$(this).text('Triggered ajaxError handler.');
}
});
answered May 14, 2010 at 12:12
karim79karim79
340k67 gold badges414 silver badges406 bronze badges
2
You have to log the responseText:
$.ajax({
type: 'POST',
url: 'status.ajax.php',
data: {
deviceId: id
}
})
.done(
function (data) {
//your code
}
)
.fail(function (data) {
console.log( "Ajax failed: " + data['responseText'] );
})
answered Sep 25, 2019 at 11:55
In case you want to utilize .then() which has a subtle difference in comparison with .done() :
return $.post(url, payload)
.then(
function (result, textStatus, jqXHR) {
return result;
},
function (jqXHR, textStatus, errorThrown) {
return console.error(errorThrown);
});
answered Sep 13, 2020 at 22:57
panagiotispanagiotis
1,5211 gold badge9 silver badges8 bronze badges
you attach the .onerror handler to the ajax object, why people insist on posting JQuery for responses when vanila works cross platform…
quickie example:
ajax = new XMLHttpRequest();
ajax.open( "POST", "/url/to/handler.php", true );
ajax.onerror = function(){
alert("Oops! Something went wrong...");
}
ajax.send(someWebFormToken );
answered Mar 2, 2020 at 22:01
Mark GiblinMark Giblin
1,0862 gold badges13 silver badges20 bronze badges
2
When an AJAX request is submitted to a site, server-side errors are easily handled with the jQuery promise approach. .done(), .fail(), etc. However for some requests (e.g. to an invalid site or one that doesn’t accept cross-origin requests), an exception occurs immediately as the call is made. Here’s an example of one error in the console:
XMLHttpRequest cannot load
http://someotherserver/api/blahblah. Origin
http://localhost:52625is not allowed by Access-Control-Allow-Origin.
Yes, I know about CORS…that’s not the issue. What I’m actually doing is trying a web api call to test if the server IP/name is correct
I’m aware of the error option in the jQuery request syntax:
$.ajax({
url: remoteURL,
type: 'GET',
error: function (err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).etc.etc.
The error is handled here, but exceptions are still logged in the console. It seemed reasonable to wrap the above in a try-catch block, but that doesn’t seem to help.
I’ve found this question, but the solution involves hacking the jQuery code. Surely there’s a better way to catch these errors and not clog up the console logs??
Промис, который возвращает fetch,
завершается с ошибкой, только если произошла
ошибка сети. Если же сервер вернул ответ
со статусом 404 или 500,
то промис будет завершен успешно,
но при этом статус ok будет
установлен в false.
Давайте перехватим оба типа ошибок:
button.addEventListener('click', function() {
let promise = fetch('/ajax.html')
.then(
response => {
if (response.ok) {
return response.text();
} else {
console.log('плохой статус ответа');
return '';
}
},
).then(
text => {
console.log(text);
}
).catch(
error => {
console.log(error);
}
);
});
Сделаем так, чтобы ошибка, связанная
с плохим статусом HTTP ответа, также
ловилась блоком catch.
Для этого прокинем ее дальше
через throw:
button.addEventListener('click', function() {
let promise = fetch('/ajax.html')
.then(
response => {
if (response.ok) {
return response.text();
} else {
throw new Error('плохой статус ответа');
}
},
).then(
text => {
console.log(text);
}
).catch(
error => {
console.log(error);
}
);
});
Выведите текст страницы, если запрос
был успешным, и ошибку, если
что-то пошло не так.
This is a tutorial on how to handle errors when making Ajax requests via the jQuery library. A lot of developers seem to assume that their Ajax requests will always succeed. However, in certain cases, the request may fail and you will need to inform the user.
Here is some sample JavaScript code where I use the jQuery library to send an Ajax request to a PHP script that does not exist:
$.ajax({
url: 'does-not-exist.php',
success: function(returnData){
var res = JSON.parse(returnData);
},
error: function(xhr, status, error){
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage);
}
});
If you look at the code above, you will notice that I have two functions:
- success: The success function is called if the Ajax request is completed successfully. i.e. If the server returns a HTTP status of 200 OK. If our request fails because the server responded with an error, then the success function will not be executed.
- error: The error function is executed if the server responds with a HTTP error. In the example above, I am sending an Ajax request to a script that I know does not exist. If I run the code above, the error function will be executed and a JavaScript alert message will pop up and display information about the error.
The Ajax error function has three parameters:
- jqXHR
- textStatus
- errorThrown
In truth, the jqXHR object will give you all of the information that you need to know about the error that just occurred. This object will contain two important properties:
- status: This is the HTTP status code that the server returned. If you run the code above, you will see that this is 404. If an Internal Server Error occurs, then the status property will be 500.
- statusText: If the Ajax request fails, then this property will contain a textual representation of the error that just occurred. If the server encounters an error, then this will contain the text “Internal Server Error”.
Obviously, in most cases, you will not want to use an ugly JavaScript alert message. Instead, you would create an error message and display it above the Ajax form that the user is trying to submit.
JQuery 3.0: The error, success and complete callbacks are deprecated.
Update: As of JQuery 3.0, the success, error and complete callbacks have all been removed. As a result, you will have to use the done, fail and always callbacks instead.
An example of done and fail being used:
$.ajax("submit.php")
.done(function(data) {
//Ajax request was successful.
})
.fail(function(xhr, status, error) {
//Ajax request failed.
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage);
})
Note that always is like complete, in the sense that it will always be called, regardless of whether the request was successful or not.
Hopefully, you found this tutorial to be useful.
The purpose of this article is to demonstrate how we handle the exception in the jQuery AJAX request. A basic understanding of HTML, CSS, and jQuery is required. This can be done by an AJAX fail() method. We discuss 3 AJAX methods to better understand what’s going on when making any ajax() request from our web browser to a particular server.
AJAX: AJAX is an acronym for “Asynchronous JavaScript and XML”. The Ajax component exploits this ability of JavaScript to send asynchronous HTTP requests, receive the XML response (as well as other formats), and update part of a website (using JavaScript) without reloading or refreshing the entire site.
The three methods that we need to know to make AJAX requests are as follows.
This method is called when an HTTP request is successful.
$.ajax(options).done(callback)
This method is called when an HTTP request fails.
$.ajax(options).fail(callback)
This method is called always, be the HTTP request fails or is successful.
$.ajax(options).always(callback)
Example: We are going to see how to use AJAX fail() methods to handle the error in the HTTP requests. The fail() callback takes 3 parameters where the first parameter is a JSON error object, the second parameter is given a reason in text format and the last parameter is for the error thrown by the HTTP request. The whole object with values of the different parameters is shown in the text area. The output is shown in JSON format to show you the value and type of the value that is received as a parameter when an HTTP request fails.
The format of the output is as follows.
"firstparam": {
value: -> the value of the first parameter
type: -> the type of the first parameter
},
"secondparam": {
value: -> value of second parameter
type: -> the type of the second parameter
},
" thirdparam": {
value: -> value of third parameter
type: -> the type of the third parameter
}
Example: In this example, we will see how to handle exceptional handling AJAX.
HTML
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src=
</script>
<style>
.container {
display: flex;
justify-content: center;
}
h1 {
color: green;
}
textarea {
margin-top: 10px;
width: 300px;
height: 300px;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
var obj = "";
$.ajax("gfg.txt").done(function () {
alert("success");
}).fail(function (errorobj, textstatus, error) {
obj = JSON.stringify({
firstparam: {
value: errorobj,
type: typeof (errorobj)
},
secondparam: {
value: textstatus,
type: typeof (textstatus)
},
thirdparam: {
value: error,
type: typeof (error)
}
}, undefined, 1);
}).always(function () {
$('textarea').val(obj);
});
});
</script>
</head>
<body>
<h1 class="container">
GeeksforGeeks
</h1>
<div class="container">
<textarea></textarea>
</div>
</body>
</html>
Output:
Last Updated :
10 May, 2023
Like Article
Save Article

