allowing another same ajax request only after the first request finished - ajax

I'm working with prototype.js and have the code like below..
new Ajax.Request('url', {
asynchronous: true,
method: "get",
onSuccess: Succeeded,
onFailure: Error
});
Problem occurs if the first requests' finishing and the next same request issued.
How can I prevent requests with same url issued unless 'Succeeded' is called?
Of course, I can fix the problem by making the change of 'asynchronous: false', but is it possible asynchronous method still applies given the situation?
Thanks,

I always use asynchronous requests, as a synchronous request is rarely what you want.
I'm curious as to why the same request could be done more than once. Usually I just repeat the request in the error callback and signal success in the success callback. I use an abort timeout so I'm not waiting forever (default HTTP timeout is 2 minutes usually).
If the request is user initiated and therefore could happen more than once, you'd have to do this check manually (set an "inProgress" boolean somewhere).

Related

When to use async false and async true in ajax function in jquery

When to use use async false or async true in an ajax call. In terms of performance does it make any difference ?
example :
$.ajax({
url : endpoint,
type : "post",
async : false,
success : function(data) {
if (i==1){
getMetricData(data)}
else if (i==2)
{
capture = data;
}
}
});
It's not relative to performance...
You set async to false, when you need that ajax request to be completed before the browser passes to other codes:
<script>
// ...
$.ajax(... async: false ...); // Hey browser! first complete this request,
// then go for other codes
$.ajax(...); // Executed after the completion of the previous async:false request.
</script>
When async setting is set to false, a Synchronous call is made instead of an Asynchronous call.
When the async setting of the jQuery AJAX function is set to true then a jQuery Asynchronous call is made. AJAX itself means Asynchronous JavaScript and XML and hence if you make it Synchronous by setting async setting to false, it will no longer be an AJAX call.
for more information please refer this link
It is best practice to go asynchronous if you can do several things in parallel (no inter-dependencies).
If you need it to complete to continue loading the next thing you could use synchronous, but note that this option is deprecated to avoid abuse of sync:
jQuery.ajax() method's async option deprecated, what now?
In basic terms synchronous requests wait for the response to be received from the request before it allows any code processing to continue. At first this may seem like a good thing to do, but it absolutely is not.
As mentioned, while the request is in process the browser will halt execution of all script and also rendering of the UI as the JS engine of the majority of browsers is (effectively) single-threaded. This means that to your users the browser will appear unresponsive and they may even see OS-level warnings that the program is not responding and to ask them if its process should be ended. It's for this reason that synchronous JS has been deprecated and you see warnings about its use in the devtools console.
The alternative of asynchronous requests is by far the better practice and should always be used where possible. This means that you need to know how to use callbacks and/or promises in order to handle the responses to your async requests when they complete, and also how to structure your JS to work with this pattern. There are many resources already available covering this, this, for example, so I won't go into it here.
There are very few occasions where a synchronous request is necessary. In fact the only one I can think of is when making a request within the beforeunload event handler, and even then it's not guaranteed to work.
In summary. you should look to learn and employ the async pattern in all requests. Synchronous requests are now an anti-pattern which cause more issues than they generally solve.

EXTJS 4: Selective Ajax Request Aborting

In my application I have many ajax request that executes every now and then. I have one that executes with a settimeout another is with a user interaction. My problem is the user interaction part.
The scenario is when the user sets the parameter and clicks the button it executes a ajax request. If he makes a mistake with its parameter the user will adjust something and then execute again the ajax request, with the previous request still on going.
I want to abort the previous request without using the abortall() because like I said before there are other request that should not be interrupted. So its like selecting a request to abort. How do I do that? Please Help.
There is a property on Ext.Ajax autoAbort : Boolean
Whether a new request should abort any pending requests.
Defaults to: false
Available since: 1.1.0
set this prop to true on your Ajax sent by user, so it will not interfere with setInterval ajax's. Also, make sure that you have a client side and a server side validation, so bad params will be avoided. Solving bad params on client side is much quicker, cheaper and user friendly thing to do than let user submit falsy data!
Ext.Ajax.request({
url: '/echo/json/',
params: {
id: 1
},
autoAbort : true,
success: function(response){
//do something
},
failure:function(response){
//do something
}
});
Here is example on fiddle!

Jquery async calls block page reload

I have a function that performs a backup every 5 seconds. From time to time the target server of the backup is not reachable and the request stops until the timeout is reached.
Since this affects the user interface I execute this 'backup function' as a async ajax request.
setInterval("doSync()", 5000 );
function doSync() {
$.ajax({
url: "backup.php",
async : true
});
};
This runs pretty good in the background.
But as soon as a reload of the page is executed, already waiting backup function calls will be completed. So in the worst case, if I have a backup with 30 seconds timeout, the user has to wait this 30 seconds before the new page is loaded.
That is not acceptable for the user.
Which strategy can I implement to avoid this?
It would be ok to terminate the backup request...
I think that issue is rather specific to the browser.
Indeed, most of them limit the number of parallel requests to the same host and that's why it "waits" before reloading the page.
If you're calling the exact same URL via your AJAX request as the one you're trying to reload, Firefox will not run more than ONE request at the same time. A simple workaround is to append a random query string to the URL.
Another option is to use the javascript beforeunload event to cancel your AJAX request : Abort Ajax requests using jQuery
I would maybe think about setting timeout in your case.
I also found similar problem already solved: click

How long will the browser wait after an ajax request?

How long can the browser wait before an error is shown before server answers for request? Can this time be unlimited?
If you are using a jQuery $.ajax call you can set the timeout property to control the amount of time before a request returns with a timeout status. The timeout is set in milliseconds, so just set it to a very high value. You can also set it to 0 for "unlimited" but in my opinion you should just set a high value instead.
Note: unlimited is actually the default but most browsers have default timeouts that will be hit.
When an ajax call is returned due to timeout it will return with an error status of "timeout" that you can handle with a separate case if needed.
So if you want to set a timeout of 3 seconds, and handle the timeout here is an example:
$.ajax({
url: "/your_ajax_method/",
type: "GET",
dataType: "json",
timeout: 3000, //Set your timeout value in milliseconds or 0 for unlimited
success: function(response) { alert(response); },
error: function(jqXHR, textStatus, errorThrown) {
if(textStatus==="timeout") {
alert("Call has timed out"); //Handle the timeout
} else {
alert("Another error was returned"); //Handle other error type
}
}
});​
Yes and no. Yes the server can do it or be configured to do so, no the browsers (i dont know about version/distributor specifics) may have timeouts enabled.
There are 2 solutions though for achieving/emulating this over HTTP:
If this is simple a long running script and you're waiting for results this isnt the way to go, you should instead do as previous poster mentioned and use async processing with server polling for the results, this would be a much more sure fire solution. For example: a thumbnail script from an image processor server side: the user uploads an image, the server immediately returns a 200 and a "Job ID". The client (javascript^^) can then use the JobID to request the job status/result.
If your goal is to have something like a realtime connection between browser and server (1 way connection, once the request is made by the browser no further info can be sent without using new requests (ajax^^)), this is called long polling/reverse ajax and can be used for real-time communication over http. There are several techniques using 2 long polled requests in parallel so that once one of them timeout the second one becomes the active and the first one attempts to reconnect.
Can you explain a bit more about what you're trying to achieve - do you have a long running process on a server, do you want to change the settings on just a local machine or are you after a way to manage it for large numbers of users?
How long the browser will wait depends on a number of factors e.g. where the timeout occurs - is it at the TCP level, the server or the local browser?
If you've got a long running process on a server and you want to update a webpage afterwards the typical way to handle it is to run the long process asynchronously and notify the client when it's complete e.g. have an ajax call that polls the server, or use HTTP 1.1 and serve out a notification stream to the client.
In either case it's still possible for the connection to be closed so the client will still need the ability to re-open it.
I found, that in case of a normal (HTML page) request, browsers run to timeout after cca. 30 secs. It's important, because other participiants probably follows it: proxies, routers (do routers play in this game? I'm not sure). I am using 4 sec long server-side delay (if there's nothing to send to the client), and my AJAX client performs another HTTP request immediatelly (I am on local network, there's no internet lag). 4 sec is long enough to not to overload the server and network with frequented polls, and is short enough for the case, when somehow one poll falls out of the row which the client can't detect and handle.
Also, there're other issues with comet (long HTTP request): browser's limit on number of simultaneous HTTP request, handling of client-side events (must sent to the server immediatelly), server/network down detection and recovery, multi user handling etc.

Long Running Wicket Ajax Request

I occasionally have some long running AJAX requests in my Wicket application. When this occurs the application is largely unusable as subsequent AJAX requests are queued up to process synchronously after the current request. I would like the request to terminate after a period of time regardless of whether or not a response has been returned (I have a user requirement that if this occurs we should present the user an error message and continue). This presents two questions:
Is there any way to specify a
timeout that's specific to an AJAX
or all AJAX request(s)?
If not, is there any way to kill the current request?
I've looked through the wicket-ajax.js file and I don't see any mention of a request timeout whatsoever.
I've even gone so far as to try re-loading the page after some timeout on the client side, but unfortunately the server is still busy processing the original AJAX request and does not return until the AJAX request has finished processing.
Thanks!
I think it won't help you to let the client 'cancel' the request. (However this could work.)
The point is that the server is busy processing a request that is not required anymore. If you want to timeout such operations you had to implement the timeout on the server side. If the operation takes too long, then the server aborts it and returns some error value as the result of the Ajax request.
Regarding your queuing problem: You may consider to use asynchronous requests in spite of synchronous ones. This means that the client first sends a request for starting the long running process. This request immediately returns. Then the client periodically polls the server and asks if the process has finished. Those poll requests also return immediately saying either that the process is still running or that it has finished with a certain result.
Failed solution: After a given setTimeout I kill the active transports and restart the channel, which handles everything on the client side. I avoided request conflicts by tying each to an ID and checking that against a global reference that increments each time a request is made and each time a request completes.
function longRunningCallCheck(refId) {
// make sure the reference id matches the global id.
// this indicates that we are still processing the
// long running ajax call.
if(refId == id){
// perform client processing here
// kill all active transport layers
var t = Wicket.Ajax.transports;
for (var i = 0; i < t.length; ++i) {
if (t[i].readyState != 0) {
t[i].onreadystatechange = Wicket.emptyFunction;
t[i].abort();
}
}
// process the default channel
Wicket.channelManager.done('0|s');
}
}
Unfortunately, this still left the PageMap blocked and any subsequent calls wait for the request to complete on the server side.
My solution at this point is to instead provide the user an option to logout using a BookmarkablePageLink (which instantiates a new page, thus not having contention on the PageMap). Definitely not optimal.
Any better solutions are more than welcome, but this is the best one I could come up with.

Resources