Kill JQuery AJAX overlapping requests - javascript

Is it possible to kill a previous ajax request?
We have tabular data very adjacent to each other. On mouseover event of each data we are making a request to our server using JQuery Ajax object and showing in popup.
But as frequently we move mouse to other tabular contents previous Ajax responses are being displayed inside popups prior exact response being displayed which is meant for that tabular content.
I need when new Ajax request is generated previous request/response should be killed, so that always expected latest response is available inside popup.
I am using JQuery, PHP and Mysql to server the request.

Could you create a custom Javascript Sync object which would be shared by the function making subsequent ajax calls?
Assign a sequentially generated id as a parameter to the request call going in. Include the same id in response. On firing every request assign a new id, incremented by 1 or whatever logic. If the current id in response is not same as the one in shared object; ignore the response else render the response.
this would cleanly solve the race condition. I am not sure myself if there is a way to kill the request prematurely but it would at least not create rendering problem that you face now.

Another option would be not to initiate another request until the first is completed.

Yes and no. That is the point of Ajax. To be able to do something asynchronously. What you are wanting to do is to abort a request which destroys the idea of asynchronously. Perhaps what you can do is, if you send another request, set a value somewhere indicating the number of requests, then in the callbacks to your requests, check if the amount of request is higher than 1, if so ignore the response.

Check this AJAX Manager plugin. The XmlHttpRequest has an abort() function but jQuery doesn't have a wrapper for it.

Related

Refresh div on JSP page with Ajax call without a response

I am aware of using AJAX calls to refresh content inside a div using the response received, but in my case I have no response but still want to refresh the div.
My application has a table called 'Cart', on which when I click the delete button, it removes an item from the cart. I remove the item by sending an AJAX call to the Java servlet that updates the cart in an ArrayList. As I'm removing only one object, I dont have a response, but still want to update the cart with the removed item.
I have tried the following ways:
Redirect to the same page using servlet after updating cart array. This causes the page to reload.
request.getRequestDispatcher(target).forward(request, response); where target is index.jspx
Use $(..).load('index.jspx') to try and refresh the particular div, but this places the entire contents of index.jspx into the tiny div with the cart table.
An AJAX request (Asynchronous Javascript And XML) is sent to your server. You can define a callback for your AJAX request, that is, a Javascript function that is going to be executed once the request ended. You can also use promises for this purpose. Anyway, once you know how you can execute a function AFTER the request has completed, you need to decide whether you need information from the server.
If you are content with not receiving any meaningful answers from the server and are okay with assuming that the removal was successful, then you can simply remember which delete button was pressed, find the row which contains it and remove() it. In this case you do not need to send further requests to the server.
Otherwise, if you need to get further information from the server (because new items might have been created/modified/removed), then simply change your server-side in order to send back a JSON about the items to the client-side and refresh your table there.
You actually don't have to redirect the whole thing again. Instead of redirecting, just use response.getWriter().write(<Your updated Array>); inside doPost() or doGet() depending on which you are using.
This will send your updated array to your AJAX code, instead of refreshing the whole page.

How to refresh screen data in JavaScript without making the page slow?

I have a question in terms of code and NOT user experience, I have the JS:
$(document).on( "click", "input:radio,input:checkbox", function() {
getContent($(this).parent(),0);
});
The above JS gets the contents from radios and checkboxes, and it refreshes the page to show dependencies. For example if I check on yes, and the dependency is on yes, show text box, the above works!
What I want to know is, if there is a better way to do the same thing, but in a more friendly way, as this is at times, making the pages slow. Especially if I do a lot of ticks/checks in one go, I miss a few, as the parent refreshes!
If you have to hit your server to getContent() then it will automatically be slow.
However, you can save a lot if you send all the elements once instead of hitting the server each time a change is made.
Yet, if creating one super large page is not an option, then you need to keep your getContent() function, but there is one possible solution, in case you did not already implement such, which is to cache all the data that you queried earlier.
So you could have an object (a map) which has keys defining the data you're interested in. If the key is defined, then the data is already available and your return and use that data directly from the cache. Otherwise, you have to hit the server.
One thing to do, you mentioned slowness as you 'tick' things back and forth, is to not send more than one request at a time to the server (with a timeout in case the server never replies). So the process here is:
Need data 'xyz'
Is that data already cached? if yes, then skip step (3 and 4)
If a request being worked on? if yes, push the data on the request stack and return
Send a request to the server, which blocks any further request until answer for 'xyz' is received
Receive the answer and cache the data in an object (map) and release the request queue
Make use of data as required
I check the request queue, if not empty pop the next request and start processing from (2)
The request process is expected to be run on a timer because (1) it can time out and (2) it need to run in the background (not GUI preemptive)

Question about make several request to a server using AJAX?

How i can make several requests to a server all at the same time, but preventing the mix of the responses?
Each of the ajax requests is made separately and you should set them up so that they go to different handlers when the ajax request is finished. The handlers may not be called in the same order since each may take longer than another.
If your code requires that they come back in the same order, you should create a single call that returns all the values you need. Or you need to queue the responses until they have all been processed

From ELements Loaded or not?

Hi I make randomly calling multiple ajax calls.how i can check all ajax calls are completed and values get loaded in combox and multiple boxes,PLease give any solution other than ajax status,Any javascript event which triggers when all elements loaded???,I tried prototype document.observe("dom:loaded", function() but its not working for ajax calls
how i can check all ajax calls are completed and values get loaded in combox and multiple boxes,PLease give any solution other than ajax status
Why? What's wrong with using the AJAX request status, which is the canonical way to determine the status of the request (and thus success or failure)?
There might be a legitimate reason for this restriction (though at first glance it appears not), but if so then it's because you're doing something unusual, such as making requests that you expect to "fail". If this is the case, then you'd need to make clear exactly what the constraints are anyway.
Failing that, just check the status and ensure that the remote server is returning the right status for requests (if it's under your control).

jQuery: Using a single Ajax call, receive progressive statuses instead of one single response?

I'm just wondering..is it possible to receive multiple responses from a single ajax call?
I'm thinking purely for aesthetic purposes to update the status on the client side.
I have a single ajax method that's called on form submit
$.ajax({
url: 'ajax-process.php',
data: data,
dataType: 'json',
type: 'post',
success: function (j) {
}
});
I can only get one response from the server-side. Is it possible to retrieve intermittent statuses? Such as:
Default (first): Creating account
Next: Sending email confirmation
Next: Done
Thanks for your help! :)
From a single ajax call, I don't think it is possible.
What you could do is check frequently where the process is (it's what is used for the upload bars in gmail for example). You do a first ajax request to launch the process, and then a series of ajax request to ask the server how he is doing. When the server answers "I'm done", you're good to go, and until that you can make the server respond and say the current state.
There is something called comet which you can set up to "push" requests to client, however it is probably way more than what you are wanting to invest in, time-wise.
You can open up a steady stream from the server, so that it continues to output, however I'm not sure how client-side script can handle these as individual "messages". Think about it like a server that outputs some info to the browser, does more work, outputs some more to the browser, does more work, etc. This shows up more or less in real time to the browser as printed text. It is one long response, but it is still one response. I think ajax only handles a response once it finished being sent, but maybe someone else will know more than me on the topic.
But you couldn't have the server output several individual responses without reloading itself, at least not with PHP, because once you start outputting the response, the response has begun and you can't chop that up without finishing the response, which happens when the script is done executing.
Your best bet is with the steady stream, but again, I'm not sure how ajax handles getting responses in chunks.
Quick Update
Based on the notes for this plugin:
[http://plugins.jquery.com/project/ajax-http-stream]
things don't look promising. Specifically:
Apparently the trend is to disallow access to the xmlhttprequest.responseText before the request is complete (stupid imo). Sorry there's nothing I can do to fix this
Thus, not only can you not get what you want in one request, you probably can't get it multiple requests, unless you want to break up the actual server-side process into several parts, and only have it continue to the next step when an ajax function triggers it.
Another option would be to have your script write it's status at specific points to another file on the server, call it "status.xml" or "status.txt". Have your first ajax function initialize the process, and have a second ajax function that queries this status file and outputs that to the user.
It is possible, but it has more to do with your backend script. As Anthony mentioned there is a tech called comet. Another term I've heard is called "Long polling". The idea is that you delay the time in which your php(insert language of choice) script finished processing.
In php you can do something like this:
while($response !== 'I'm done'){
sleep(1);
}else{
return $some_value;
exit();
}
This code stops your script from completely finishing. sleep(1) allows the script to stop and lets the server rest for 1 millisecond, before it loops back through. You can adjust the sleep time based on your needs. In php the amount of time the script sleeps is not counted agains your server timeout time.
You'll obviously need to make more checks for you code. You'll probably also want to allow for an abort script call. Something like sending a get request to kill the backend script. Maybe on the javascript unload event.
In the tests that I've done. I made the initial ajax call, and when the value was returned, I made another ajax call, that way your back end script wont time out.
I've only played around with this on my local server, so i'm not sure how real world this is, but it works.

Categories

Resources