Prevent Stale Ajax Data with jQuery


/ Published in: jQuery
Save to your folder(s)

When running live filters on large, long scripts you can get old, stale results replacing your new, fresh ones. After all, a search for everything containing 'S" in a large database of city names can take a lot longer than "Seattle", so your script gets the results for "Seattle", displays then, then it gets the results for "S" and displays them, replacing the "Seattle" search you really wanted.

This script aborts the previous call before making the new one, effectively preventing that from happening. There are 2 caveats though.

1. The server may continue to process the request (depending on setup).
2. The error console logs it as an error, but not a fatal one and no alerts are thrown so the normal end user wont notice.

I have some more information available at the URL.


Copy this code and paste it in your HTML
  1. function ajax_get(){
  2. if(getting!=''){getting.abort();}
  3. $('#loading_animation').fadeIn();
  4. filter = $.get('/path/to/ajax.file', function(data) {
  5. $('#ajax_container').html(data);
  6. $('#loading_animation').fadeOut();
  7. });
  8. }

URL: http://fatfolderdesign.com/181/code/prevent-stale-ajax-data-in-jquery

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.