I am trying to do a connection check for a form before it is submitted, when the button is clicked on. The idea is to look through a Timeout request "Timeout()..." which is not implemented yet in this code, and keep iterating through the Ajax until a connection is found, as sometimes out in the field the connection can drop. When a connection is found it will alert the user and will submit successfully if there was a dropped connection after hitting submit. Here is what I have so far:
function upload_prepformDiff() {
$.ajax({
type: 'POST',
url: './php/upload_prepform.php',
timeout: 2000, //2 seconds, for testing purposes
data: prepform,
async: false,//Omitted now as of this post
dataType: 'text',
success: function() {
alert("Your Prep form has been submitted.");
window.top.location.replace('./');
},
error: function (xhr, status, error) {
if(status == "timeout") {
alert("Internet connection has been lost! Please wait until you are notified and do not continue.");
} else {
alert(status + " " + error);
}
}
});
};
The issue is that even with a low timeout value, I do not get a "timeout" status message I get "error." So it never throws the timeout error I need and for error I get: Error: NETWORK_ERR: XMLHttpRequest Exception 101
So the ajax does notice there is no connection, but that is what the errorThrown shows, while the textStatus is "error" for (xhr, status, error) respectively. So what I TRIED doing was do a little improvising and do some type of error.indexOf() deal with the error string thrown in the Ajax, but that didn't work nor did error.contains("NETWORK_ERR") or any type of Regex command. Any ideas for improving this or why I am not getting a timeout? Thanks!
Guess this might be a bit late for you, but nevertheless...
If you have specified
async as 'false'
, the timeout property will be ignored.
As for handling the errors, you can visit an earlier SO question:
status of ajax or post request
Hope this helps! :)
Related
I'm utilizing the magic of jQuery.ajax( settings ).
However, I'm wondering if anyone has played with the timeout setting much?
I know it's basically for dictating the local time for a request, but can it trigger anything if the timeout is reached? Or does it simply stop listening for a response?
Reading the jQuery site, I can see there are no arguments passed, so it seems like a simple setting with one capability. Which is fine.
But, I'd like to trigger an alert or some function if the timeout is reached. I can see that the error setting doesn't get triggered, in this case.
Here's my snippet:
$("form#testform").submit(function(){
var allFormValues = $("form#testform").serialize();
$.ajax({
cache:false,
timeout:8000, // I chose 8 secs for kicks
type:"POST",
url:"someurl.php",
data:allFormValues,
error:function(){ alert("some error occurred") },
success:function(response){ alert(response); }
});
});
Does anyone know how to work more with timeout?
If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.
Per the jQuery documentation:
Possible values for the second
argument (besides null) are "timeout",
"error", "notmodified" and
"parsererror".
You can handle your error accordingly then.
I created this fiddle that demonstrates this.
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 1000,
success: function(response) { alert(response); },
error: function(xmlhttprequest, textstatus, message) {
if(textstatus==="timeout") {
alert("got timeout");
} else {
alert(textstatus);
}
}
});
With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.
Hope this helps!
I am sending lots of data using jquery ajax method to web sever and client side respond only after receiving acknowledgment from server, now suppose network connection lost in MIDDLE of ajax call then how to detect this situation.
$.ajax({
url:'server.php',
data:'lots of data from 200KB to 5MB',
type:'post',
success: function(data)
{
alert('Success');
//some stuff on success
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Failure');
//some stuff on failure
}
});
This is my code and and it does not give error in middle of ajax call if get internet is disconnected.
NOTE : I cant use time out because data size is vary from 200kb to 5MB and server response time calculation is not feasible.
Try this:
First create a "ping" ajax call with setInterval every 5 seconds
function server_ping()
{
$.ajax({
url:"url to ping",
type: "POST"
});
}
var validateSession = setInterval(server_ping, 5000);
then arm your .ajaxError trap:
$(document).ajaxError(function( event, request, settings ) {
//When XHR Status code is 0 there is no connection with the server
if (request.status == 0){
alert("Communication with the server is lost!");
}
});
Remember Ajax calls are Asynchronous by default, so when the pings are going to the server and the request cannot reach the server the value on the XHR status is 0, and the .ajaxError will fire and you must catch the error and handle the way you want it.
Then you can send your data to the server, if the connection is lost when sending the data you get the error reported by the ping.
If your server was not very crowded, probably you could use a timer to start detecting the connection regularly when you start transferring the data (by using another ajax calling, for instance each 5 seconds). now you can use timeout.
Btw,
1)timeout doesn't always means network error. sometimes server's down also causes "timeout"
2)if the driver is down on client device, xhr.status = 0, and no timeout
I had a similar problem and solved it with a simpel try/catch and a re-try delay of (say) 2 seconds:
function myAjaxMethod()
{
try
{
$.ajax({ ... });
} catch (err)
{
console.log(err.message);
setTimeout(function(){myAjaxMethod(),2000});
}
}
I faced a similar situation like yours and fixed it by having a network check for every 5 seconds and if network is disconnected i would abort the ajax request manually which will end the ajax request.
Here i get the ajax XmlHttpRequest in the beforeSend event of the Jquery ajax call and use that object to abort the ajax request in case of network failure.
var interval = null;
var xhr = null;
$.ajax({
beforeSend: function(jqXHR, settings) {
xhr = jqXHR; // To get the ajax XmlHttpRequest
},
url:'server.php',
data:'lots of data from 200KB to 5MB',
type:'post',
success: function(data)
{
alert('Success');
//some stuff on success
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Failure');
//some stuff on failure
},
complete: function(data)
{
alert('Complete');
//To clear the interval on Complete
clearInterval(interval);
},
});
interval = setInterval(function() {
var isOnLine = navigator.onLine;
if (isOnLine) {
// online
} else {
xhr.abort();
}
}, 5000);
Try adding timeout: while constructing your $.ajax({}).
Also make sure to set cache: false, helpful sometimes.
Refer to Jquery's ajax() : http://api.jquery.com/jQuery.ajax/#toptions
You will get much more information there!
My thought s on your problem[updated]
#RiteshChandora , I understand your concern here. How ever I can suggest you to do 2 things.
As you have post data ranging from 200kb to 5mb, you might want to choose a maximum timeout. and trigger for the same. Yes, this might be problematic, but with the design you chosen, the only way to monitor the POST progress is to do this way. if not, see point 2.
I went through the flow, you are asking the user to copy the response Json from FB to your url. there are some problems here,
The json data has sensitive information about the user, and he is posting it on a url without SSL encryption.
Why should you prompt the user to post the acquired data on to your server? it should be easier if you user sever side scripts. Also you should never post huge data from the client to the server in occasions like these, where you could retrieve the same form the FBserver->your sevrer on the server side.
My suggested solution : after the user is authenticated , retrieve his friends list on the server side. do whatever you want on the server side, and display the result on the users screen.
This way all the burden will be taken by your server, also there is no need for the user to do any nasty json posting on your url.
Btw, your app idea is cool.
error: function(xhr, textStatus, thrownError)
{
alert(xhr.status);
alert(thrownError);
alert(textStatus);
}
Try them..
TextStatus (besides null) are "timeout", "error", "abort", and "parsererror".
When an HTTP error occurs, thrownError receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error."
If Internet disconnects,the response wont be received and maximum it would be a timeout message..
I have the following:
$.ajax({ cache: false,
url: "/Admin/Contents/GetData",
data: { accountID: AccountID },
success: function (data) {
$('#CityID').html(data);
},
error: function (ajaxContext) {
alert(ajaxContext.responseText)
}
});
When I lose connectivity to the internet the error is called but I don't see anything in the responseText.
Is there a way I can find out different kind of errors based on status information in the returned ajaxContent? I would really like to be able to put out a message saying "Internet connectivity lost" and another message if there is some other problem.
According to the jQuery docu the error function receives three arguments:
jqXHR:
textStatus: a string describing the type of error that occurred
errorThrown: an optional exception object, if one occurred
Furthermore it states:
Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error."
So you might want to have a look at the content of the second adn third parameter.
$.ajax({ cache: false,
url: "/Admin/Contents/GetData",
data: { accountID: AccountID },
success: function (data) {
$('#CityID').html(data);
},
error: function (ajaxContext) {
if(ajaxContext.status=="404")
{
//write your not found handler code here
}
else
alert(ajaxContext.status)
}
});
Updated.
You should just add: timeout: , somewhere within $.ajax({}). Also, cache: false, might help in a few scenarios.
$.ajax is well documented, you should check options there, might find something useful.
JQuery Ajax - How to Detect Network Connection error when making Ajax call
if you mean defferent kinds of response results it's here - http://api.jquery.com/jQuery.ajax/ - statusCode parameters
Im having a very weird issue.
I have a normal ajax call that upload the avatar you choose from your pc up to the server..
this works sometimes, sometimes i can see in firebug under the Net that after some time loading, it gets "Aborted" and marked in red.
i even have a ajaxstart ajaxend loader icon and the icon keeps showing even when it gets aborted.
Why is this happening, and how can i prevent it from aborting? And maybe how can i make a "try again" if it got aborted?..why is it even aborted :S
Ive noticed it happening on bigger demension/size files? And on the file it request(fileupload.php) i do have a checker there, to callback an error if its bigger. But i think it does not even get to the file before it "lags" and stops..
Update confirmed: this occurs when i try to ajax send file with bigger size..
How are you sending files through Ajax? Ajax does not support sending files.
If it is a connection timeout in jQuery console it will show in red color and the failure handler of the ajax request will be called.
You can handle any conditions you want there. To remove timeout issue you can add a attribute timeout to your ajax request. I think the default value is 30 seconds
$.ajax({
url : "",
data : {},
success : function(data, textStatus, XMLHttpRequest){
},
error: function(XMLHttpRequest, textStatus, errorThrown){
if(textStatus == "timeout"){
alert("timeout")
}
},
timeout : 600000
});
Since you are using ajaxfileupload try this
$.ajaxFileUpload({
.....,
timeout: 60000,
error: function (data, status, e)
{
if(status == "timeout"){
alert("timeout")
}else{
alert(status)
}
}
})
And make sure that you does not have any max file upload size set in your server.
It probably got aborted because the request timed out on the client side. Increase the timeout in jquery.
Is it possible to catch an error when using JSONP with jQuery? I've tried both the $.getJSON and $.ajax methods but neither will catch the 404 error I'm testing. Here is what I've tried (keep in mind that these all work successfully, but I want to handle the case when it fails):
jQuery.ajax({
type: "GET",
url: handlerURL,
dataType: "jsonp",
success: function(results){
alert("Success!");
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Error");
}
});
And also:
jQuery.getJSON(handlerURL + "&callback=?",
function(jsonResult){
alert("Success!");
});
I've also tried adding the $.ajaxError but that didn't work either:
jQuery(document).ajaxError(function(event, request, settings){
alert("Error");
});
Here's my extensive answer to a similar question.
Here's the code:
jQuery.getJSON(handlerURL + "&callback=?",
function(jsonResult){
alert("Success!");
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); })
.always(function() { alert('getJSON request ended!'); });
It seems that JSONP requests that don't return a successful result never trigger any event, success or failure, and for better or worse that's apparently by design.
After searching their bug tracker, there's a patch which may be a possible solution using a timeout callback. See bug report #3442. If you can't capture the error, you can at least timeout after waiting a reasonable amount of time for success.
Detecting JSONP problems
If you don't want to download a dependency, you can detect the error state yourself. It's easy.
You will only be able to detect JSONP errors by using some sort of timeout. If there's no valid response in a certain time, then assume an error. The error could be basically anything, though.
Here's a simple way to go about checking for errors. Just use a success flag:
var success = false;
$.getJSON(url, function(json) {
success = true;
// ... whatever else your callback needs to do ...
});
// Set a 5-second (or however long you want) timeout to check for errors
setTimeout(function() {
if (!success)
{
// Handle error accordingly
alert("Houston, we have a problem.");
}
}, 5000);
As thedawnrider mentioned in comments, you could also use clearTimeout instead:
var errorTimeout = setTimeout(function() {
if (!success)
{
// Handle error accordingly
alert("Houston, we have a problem.");
}
}, 5000);
$.getJSON(url, function(json) {
clearTimeout(errorTimeout);
// ... whatever else your callback needs to do ...
});
Why? Read on...
Here's how JSONP works in a nutshell:
JSONP doesn't use XMLHttpRequest like regular AJAX requests. Instead, it injects a <script> tag into the page, where the "src" attribute is the URL of the request. The content of the response is wrapped in a Javascript function which is then executed when downloaded.
For example.
JSONP request: https://api.site.com/endpoint?this=that&callback=myFunc
Javascript will inject this script tag into the DOM:
<script src="https://api.site.com/endpoint?this=that&callback=myFunc"></script>
What happens when a <script> tag is added to the DOM? Obviously, it gets executed.
So suppose the response to this query yielded a JSON result like:
{"answer":42}
To the browser, that's the same thing as a script's source, so it gets executed. But what happens when you execute this:
<script>{"answer":42}</script>
Well, nothing. It's just an object. It doesn't get stored, saved, and nothing happens.
This is why JSONP requests wrap their results in a function. The server, which must support JSONP serialization, sees the callback parameter you specified, and returns this instead:
myFunc({"answer":42})
Then this gets executed instead:
<script>myFunc({"answer":42})</script>
... which is much more useful. Somewhere in your code is, in this case, a global function called myFunc:
myFunc(data)
{
alert("The answer to life, the universe, and everything is: " + data.answer);
}
That's it. That's the "magic" of JSONP. Then to build in a timeout check is very simple, like shown above. Make the request and immediately after, start a timeout. After X seconds, if your flag still hasn't been set, then the request timed out.
I know this question is a little old but I didn't see an answer that gives a simple solution to the problem so I figured I would share my 'simple' solution.
$.getJSON("example.json", function() {
console.log( "success" );
}).fail(function() {
console.log( "error" );
});
We can simply use the .fail() callback to check to see if an error occurred.
Hope this helps :)
If you collaborate with the provider, you could send another query string parameter being the function to callback when there's an error.
?callback=?&error=?
This is called JSONPE but it's not at all a defacto standard.
The provider then passes information to the error function to help you diagnose.
Doesn't help with comm errors though - jQuery would have to be updated to also callback the error function on timeout, as in Adam Bellaire's answer.
Seems like this is working now:
jQuery(document).ajaxError(function(event, request, settings){
alert("Error");
});
I use this to catch an JSON error
try {
$.getJSON(ajaxURL,callback).ajaxError();
} catch(err) {
alert("wow");
alert("Error : "+ err);
}
Edit: Alternatively you can get the error message also. This will let you know what the error is exactly. Try following syntax in catch block
alert("Error : " + err);
Mayby this works?
.complete(function(response, status) {
if (response.status == "404")
alert("404 Error");
else{
//Do something
}
if(status == "error")
alert("Error");
else{
//Do something
}
});
I dont know whenever the status goes in "error" mode. But i tested it with 404 and it responded
you ca explicitly handle any error number by adding this attribute in the ajax request:
statusCode: {
404: function() {
alert("page not found");
}
}
so, your code should be like this:
jQuery.ajax({
type: "GET",
statusCode: {
404: function() {
alert("page not found");
}
},
url: handlerURL,
dataType: "jsonp",
success: function(results){
alert("Success!");
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Error");
}
});
hope this helps you :)
I also posted this answer in stackoverflow - Error handling in getJSON calls
I know it's been a while since someone answerd here and the poster probably already got his answer either from here or from somewhere else. I do however think that this post will help anyone looking for a way to keep track of errors and timeouts while doing getJSON requests. Therefore below my answer to the question
The getJSON structure is as follows (found on http://api.jqueri.com):
$(selector).getJSON(url,data,success(data,status,xhr))
most people implement that using
$.getJSON(url, datatosend, function(data){
//do something with the data
});
where they use the url var to provide a link to the JSON data, the datatosend as a place to add the "?callback=?" and other variables that have to be send to get the correct JSON data returned, and the success funcion as a function for processing the data.
You can however add the status and xhr variables in your success function. The status variable contains one of the following strings : "success", "notmodified", "error", "timeout", or "parsererror", and the xhr variable contains the returned XMLHttpRequest object
(found on w3schools)
$.getJSON(url, datatosend, function(data, status, xhr){
if (status == "success"){
//do something with the data
}else if (status == "timeout"){
alert("Something is wrong with the connection");
}else if (status == "error" || status == "parsererror" ){
alert("An error occured");
}else{
alert("datatosend did not change");
}
});
This way it is easy to keep track of timeouts and errors without having to implement a custom timeout tracker that is started once a request is done.
Hope this helps someone still looking for an answer to this question.