i'm pretty new to jquery ajax. i have been using it for personal projects for about 6 months now, but this is my first real "professional" application using it. so i have an application that does multiple ajax calls based upon a form and everything is working very well.
but, a few of the queries take (up to) 20 seconds to reply (mining large mysql datasets). if the user changes part of the form i need to make a few new calls, and that works fine too. the problem is the previous ajax requests that are already taking place need to be canceled. i googled this question and found a few answers on stackoverflow, but they didnt quite fit my needs so i wrote my own solution. i'd like some feedback on my implementation to see if what i doing is correct, and if there are any ways to optimize it.
so i have one single "wrapper" ajax function that all my other js functions call:
- function closure(url, data, success, error) {
- $.ajax({
- type: "POST",
- url: url,
- data: data,
- cache: false,
- success: success,
- error: error,
- beforeSend: function(jqXHR) {
- xhrPool.push(jqXHR);
- },
- complete: function(jqXHR, textStatus) {
- xhrPool = $.grep(xhrPool, function(x){return x!=jqXHR});
- }
- });
- }
i also have this method for aborting all active ajax calls:
- function abortAjax() {
- $.each(xhrPool, function(idx, jqXHR) {
- jqXHR.abort();
- });
- }
and example of using these functions would be:
- function memberInfo() {
- closure(
- 'http://<?php echo(URL); ?>/analytics/api/ajax.php',
- 'action=memberInfo',
- function(result) {
- $('#memberInfo').html(result.msg);
- },
- function(xhr, status, thrown) {
- //setupForm();
- //$('#error').html(xhr.responseText);
- }
- );
- }
- function roi() {
- $('#roi').html(' ');
- closure(
- 'http://<?php echo(URL); ?>/analytics/api/ajax.php',
- 'action=roi&time='+timeSelected+'&start='+startDate.format('YYYY-MM-DD')+'&end='+endDate.format('YYYY-MM-DD')+'&stores='+JSON.stringify(menuLocations),
- function(result) {
- $('#roi').html(numberWithCommas(result.msg));
- },
- function(xhr, status, thrown) {
- //setupForm();
- //$('#error').html(xhr.responseText);
- }
- );
- }
- function updateGUI() {
- abortAjax();
- memberInfo();
- roi();
- }
these functions are obviously edited down for simplicity.
the idea is when the updateGUI method is called, it aborts any existing ajax calls then makes new ones. i also included 2 example ajax calls from the app but there are honestly about 20-30 different ones. some are purely text/numeric others generate charts w/ D3js.
im really looking for feedback on the closure "complete" method and it's "grep" call. and the abortAjax "each" loop. do these look ok? any suggestions are welcome :D
thanx!