jQuery Ajax Call, give offline/ "not able to connect" message - ajax

Yes, i have a normal ajax call that calls imback.php, that checks for new stuff if you have been blur for 50 sec.
Now if you disconnects from the internet, and when you get on focus, it will not be able to get imback.php.(i think its 404 error) So i would like to make a offline msg/timeout thing, so it alerts "You have no internet connection or something else went wrong".
How can i do that?
$.ajax({
url: 'imback.php',
success:function(msg) {
$('.NewStuffSinceActive').prepend(msg);
}
})

You can use the error callback for this:
$.ajax({
url: 'imback.php',
success: function(msg) {
$('.NewStuffSinceActive').prepend(msg);
},
error: function(xhr, status, error) {
alert("An error occured: " + error);
}
})

Related

Catching an AJAX error from a post request (422)

I have the following Ajax but it needs to handle a 422 error being returned (which means Out of Stock). I've tried a few ways around but it error's and refuses to POST stating:
Failed to load resource: the server responded with a status of 422 ()
I'm unsure how to catch the 422 error and return something to the user displaying that it's out of stock.
Shopify.moveAlong = function() {
// If we still have requests in the queue, let's process the next one.
if (Shopify.queue.length) {
var request = Shopify.queue.shift();
var data = 'id='+ request.variant_id + '&quantity='+request.quantity_id;
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: data,
success: function(res){
Shopify.moveAlong();
},
error: function(){
// if it's not last one Move Along else update the cart number with the current quantity
if (Shopify.queue.length){
Shopify.moveAlong()
}
}
});
}
else {
window.location.href = "/cart";
}
};
Shopify.moveAlong();
I've tried a few ways around but it error's and refuses to POST.
What I have understood is, you are seeing this error in Browser console. It cannot be prevented, but it does not mean that you request is not going through. The POST request is recieved by Shopify and a response with status 422 is sent, so that is treated as an error (Non 2xx response codes are treated as error).
To handle the error and display error message, adapt the code accordingly. Check updated code and code comments.
Shopify.moveAlong = function() {
// If we still have requests in the queue, let's process the next one.
if (Shopify.queue.length) {
var request = Shopify.queue.shift();
var data = 'id=' + request.variant_id + '&quantity=' + request.quantity_id;
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: data,
success: function(res) {
Shopify.moveAlong();
},
error: function(jqXHR, textStatus, errorThrown) {
// Check status code
if (jqXHR.status === 422) {
// display error wherever you want to
console.log(jqXHR.responseText);
}
// if it's not last one Move Along else update the cart number with the current quantity
if (Shopify.queue.length) {
Shopify.moveAlong()
}
}
});
} else {
window.location.href = "/cart";
}
};
Shopify.moveAlong();
AJAX Error Docs

ajax call returning different datatypes?

I have the following ajax call:
$.ajax({
type: "post",
dataType: "html",
url: '#Url.Content("~/RBA/Tools/_Actions")',
data: $("#actionForm").serialize(),
success: function (response) {
debugger;
$("#DetailsEdit").removeClass('zoomInDown');
$("#DetailsEdit").addClass('flipInX');
$("#DetailsRefresh").html(response);
$("#actionPlaceholder").hide();
$("#dashSpinner").hide();
},
error: function (response) {
debugger;
$("#dashSpinner").hide();
swal({
title: "Error",
text: response.responseText,
type: "error",
showConfirmButton: true
});
}
});
I am having a problem with the error portion as it is returning html to me. When I run the MVC on my local machine, I am getting the error message displayed properly in a pop up box. When I deploy the application to another server, I am getting some lengthy html message which is really awkward. How do I fix this issue?
Here is my catch exception block of the controller that this ajax call is calling:
catch (Exception e)
{
log.Error(e);
if (e.Message.Contains("Is not a valid cause category."))
error = "The selected category is not a valid category. Please choose another category.";
else
error = "You cannot take this type of action.";
Response.StatusCode = 500;
return Json(error);
}
I know that my dataType in the ajax call is listed as html and I need the ajax call to return html when it is successful so that it can bring up another view. But in my error, I want to get a string so it can display the message to the sweetalert box. How do I accomplish this?
Thanks in advance
Use this:
return new HttpStatusCodeResult(500, error);
This will return a 500 INTERNAL SERVER ERROR result with your error message as the response body.
It may be necessary to include the following line of code to tell IIS to let you return 500:
Response.TrySkipIisCustomErrors = true

Express res.jsonp returns two callback names to Safari Extension AJAX call

I'm building an extension in Safari, using Express.js on the back end. I make an AJAX call to the server, and the server responds with what appears to be a double callback name:
jQuery191026131771644577384_1364321159940 && jQuery191026131771644577384_1364321159940([
{
"foo": "bar"
}
]);
Here's the AJAX:
$.ajax({
type : "GET",
data : { 'something': 'something more'},
url : "http://localhost:3001/api/login/?callback=?",
dataType: 'jsonp',
success: function(data, text){
console.log(data)
},
error: function (request, status, error) {
console.log("ERROR: " + status + error );
}
});
...and here's the Express.js:
app.get('/api/login', function(req, res){
res.jsonp([{'foo':'bar'}]);
});
The browser is reporting a parse error, likely because of the double callback stamp above.
Clues?
It's not a double callback, it's the same as doing func && func(), it just makes sure that the function exists before calling it, so avoid throwing an exception.
Hector has it right in the comments: Try removing callback=? from the URL

Why won't jQuery call my Ajax error handler?

I have the following jQuery Ajax call (There are no other global settings/handlers):
$.ajax( {
url: "http://www.blah.com/url/does/not/exist",
type: "get",
data: someData,
dataType: "json",
error: function (xhr, msg, ex)
{
alert("Failed: " + msg);
},
complete: function (xhr, msg)
{
alert("Done: " + msg);
}
I would expect my error handler to be called, but instead the complete event fires and the alert displays Done: success. In my Javascript console, I see the following message:
XMLHttpRequest cannot load http://www.blah.com/url/does/not/exist.
Origin null is not allowed by Access-Control-Allow-Origin.
Why won't my error handler get called?
What is the meaning of the Origin message logged to the console?
Thanks!
Looks like the only way is to receive the server response in my success method and store it in a global variable, which I'll check in the handler for complete (which always gets called). No response means the request failed.
It's a shoddy way of handling errors in this otherwise excellent libary.
Your error handler isn't called because the AJAX request doesn't even take place: the browser refuses to do that because of the same origin policy: the data you're requesting would come from a different site than the one serving your page.
You can try using the JSONP data type to work around the problem:
$.ajax({
url: "http://www.blah.com/url/does/not/exist",
type: "get",
data: someData,
dataType: "jsonp",
error: function(xhr, msg, ex) {
alert("Failed: " + msg);
},
complete: function(xhr, msg) {
alert("Done: " + msg);
}
});

Check status of a jQuery ajax request

It seems that the success, error, and complete callbacks only fire when the ajax request is able to get some response from the server.
So if I shut down the server the following error callback is not executed and the request fails silently.
$.ajax({
type: "GET",
url: "http://localhost:3000/",
dataType: "script",
success: function() {
alert("success");
},
error: function() {
alert("error");
}
});
What's the best way to throw an error when the server can't be reached at all.
Edit - From what I've tried and read it appears that jQuery's built in error handling doesn't work with JSONP, or dataType: "script". So I'm going to try setting a manual timeout.
Edit - Did a little more research and it looks like not only does the ajax error callback not work, but you can't abort an ajax request with dataType script or jsonp, and those requests ignore the timeout setting.
There is an alternative - the jquery-jsonp plugin, but it uses hidden iframes which I'd rather avoid. So I've settled on creating a manual timeout as suggested below. You can't abort the request if it times out, which means the script may still load even after the timeout, but at least something will fire if the server is unavailable.
You can use a setTimeout, and clear it with clearTimeout in the complete handler.
var reqTimeout = setTimeout(function()
{
alert("Request timed out.");
}, 5000);
var xhr = $.ajax({
type: "GET",
url: "http://localhost:3000/",
dataType: "script",
success: function() {
alert("success");
},
error: function() {
alert("error");
},
complete: function() {
clearTimeout(reqTimeout);
}
});
jQuery.ajax already has a timeout preference and it should call your error handler should the request time out. Check out the fantastic documentation which says — I’d quote it here, emphasis mine:
timeoutNumber
Set a local timeout (in milliseconds) for the request…
and:
error (XMLHttpRequest, textStatus, errorThrown) Function
A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror". This is an Ajax Event.
error: function (jqXHR, textStatus, errorthrown) {
if (jqXHR.readyState == 0) {
//Network error, i.e. server stopped, timeout, connection refused, CORS, etc.
}
else if (jqXHR.readyState == 4) {
//HTTP error, i.e. 404 Not found, Internal Server 500, etc.
}
}
Use readyState of XMLHttpRequest to determine the status of the ajax request.
'readyState' holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
If I remember correctly, jQuery throws exceptions. Thus, you should be able to work with a try { ... } catch() { ... } and handle it there.
You can use Jquery's AjaxSetup to handle your error handling.
$.ajax({
type: "GET",
url: "http://localhost:3000/",
dataType: "script",
success: function () {
alert("success");
}, error: function () {
alert("error");
}
//AJAX SETUP "error"//
$.ajaxSetup({
"error": function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + ' ' + textStatus + ' ' + errorThrown); //however you want
}
});
in ie8,can use:
success: function(data, textStatus, XMLHttpRequest) {
if("success"==textStatus&&XMLHttpRequest){
alert("success");
}else{
alert("server down");
}
}
but it's can't work on chrome,firefox...
i tried

Resources