Developer Snippet Diary

Cancel the previous requests if a new request using ajax made in javascript

Ajax function

<script>
var xhr =null;
function js_ajax(url, method, data, successCallback, errorCallback) {
  if (xhr !== null && xhr.readyState !== 4) {
    xhr.abort();
  }
  xhr = new XMLHttpRequest();
  xhr.open(method, url);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.onload = function() {
    if (xhr.status === 200) {
      successCallback(xhr.responseText);
    } else {
      errorCallback(xhr.statusText);
    }
  };
  xhr.onerror = function() {
    errorCallback(xhr.statusText);
  };
  xhr.send(JSON.stringify(data));
}
</script>

Function Testing

<script>
js_ajax("test1", 'GET', {}, function(response) {});
js_ajax("test2", 'GET', {}, function(response) {});
 js_ajax("test3", 'GET', {}, function(response) {}); //only this will give responce
</script>
Posted by: R GONDAL
Email: rizikmw@gmail.com