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!
Related
Dependent on a selection, made on a website, plots are generated on a server where Flask runs.
The issue that I have is that generating e.g. 10 different plots can take up to 30s. What I like to achieve is to start updating the website as soon as the first plot is ready and then load automatically the others as soon as they are ready.
Currently, the following AJAX function is executed as soon as the user hits the "process" button on the website:
$.ajax({
type: "POST",
url: "/single",
data: { athleteName1: $('#athleteName1').val(), style: $('#style').val()},
success: function (results) {
$('#results').empty().append(results);
$('#results').show();
$('#submitbutton').prop('disabled', false);
},
error: function (error) {
console.log(error);
}
});
On the server site, plots are created and embedded in div-containers. They are subsequently concatenated an returned to the website at once as "diagStr":
#app.route('/single', methods=['POST', 'GET'])
def single():
loop 10 times:
diagStr += generate_plot()
return Markup(diagStr)
Doing it with "Streaming Contents" can only be part of the solution as AJAX waits until the the entire response is received.
Any idea how this is solved with today's technology?
There are multiple way you could achieve this, but some simple examples:
do your looping on the client side, and generate 10 separate Ajax requests, updating the web page when each response is received.
if you don't know in advance on the client side, how many loops you will have, then use a single request and have the server send the response as soon as the first loop is complete, along with a flag indicating whether there are more loops or not - the client can look at this flag and create a new Ajax request if there are more loops.
I have a web-page (Django 1.9 on back-end, Apache server) with an endless-paginated table with large data set and column filters. When a user activates one filter (let's denote it CHOICE 1), and then instantly changes his mind resetting the filter (let's refer to it as CHOICE 2), I would like to tell Ajax to give up waiting for back-end response to CHOICE 1 and go on to posting and waiting for CHOICE 2 request. For this purpose, I had the following JS code:
// AJAX_GET_REQUEST is a global variable
AJAX_GET_REQUEST= $.ajax(
{
type:'GET',
url:"/my_url/",
beforeSend : function()
{
if (AJAX_GET_REQUEST!= null)
AJAX_GET_REQUEST.abort();
},
data:data,
success: function(response)
{
// Do something
}
});
Fine. I used to think that I achieved the goal of successfully canceling irrelevant requests, But I found out that AJAX_GET_REQUEST.abort(); leads to Django error [Errno 10053] An established connection was aborted by the software in your host machine. The interesting think is that this is not a 'fatal error' in that the app does not terminate, but rather it takes years for my paginated table to load. Django seems to reactivate connection itself and go on to handle last request. Finally after waiting for long time I see the correct result on front-end. If I remove the AJAX_GET_REQUEST.abort(); line, everything is fine, but I have to wait until Django is through with irrelevant requests until it goes on to handle the last relevant request.
Is there any way out? Is it possible to abort previous requests avoiding this annoying 10053 error ?
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.
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).
I have a client ( written in JS-jQuery ) sending 4 requests to a server ( written in ASP.NET-C# ).
The first 3 requests work fine; but the last one is empty when received server side.
When i use firebug to see the request sent by the client, it looks fine, but the server still receive an empty QueryString;
When i do a "Step by step" debugging with firebug, the server gets the correct request.
I thought it was a Cross Domain problem, but in that case all the 4 requests should not work !!
Have you ever had a similar problem ? How can i solve this problem ?
Thanks for your answer.
Setting async: false has other implications.
If you set async to false the browser will bet blocked till the response comes back to the client from the server, this will impact the client performance and user experience. If you can share the piece of code which is causing the problem we may be able to help you to solve it. Setting async to false may not be the right solution.
Can you share some details regarding the following points
What is the order in which the requests are made?
Is all request independent or some requests are depending on other requests response value?
The chances of the 4th ajax request(the one which fails) depending on another request(1 of the first 3) is very much because you are saying if you set the async to false the request is working fine.
In this case I would suggest something like
$.ajax({
url: 'request whose result need to be used in the 4th request',
data:{....}
....
}).success(function(result){
$.ajax({
url : '4ht request',
data:{
xyx : result.abc,
......
}
});
})