Question

How can I call my function: myFunc1 in jquery after the browser has completely sent an ajax request?

I want to run a callback function after a jquery ajax has been sent. I don't want to do this on complete or success because I don't want to wait for the request to complete. I want to fire it right after the ajax request has been sent from the browser.

This is use case for which i need this:

I want run a function after making an ajax request. My original code was this:

  $.ajax({url: 'x.html'});
  myFunc1();

In the case when `myFunc1() changes the browsers location, the browser would cancel the pending ajax request.

My current solution is to do this:

  $.ajax({url: 'x.html', complete: myFunc1});

This makes sure that myFunc1 is not called till the ajax is complete. Although this solution works, it is inefficient because myFunc1 wont run till the request is complete. Since I don't care what the ajax request returns, whether it fails or succeeds, I dont need to wait for it to complete to run the myFunc1 function.

Was it helpful?

Solution 3

This is what i did to run my callback function sufficiently after the AJAX call had been made so the browser doesn't cancel it and without having to wait for the server to complete the resquest:

  var cb = function(){
    window.document.location.href="http://google.com";
  }

  $.ajax({
    url: 'x.html',
    complete: cb,
    timeout: 100
  });

Here the timeout makes sure that if my server doesn't repond in 100ms, the callback is executed. 100ms also is sufficient time for the browser to send the request.

I experimented with status codes and finally ended up not using them. I found them to unreliable cross browser and for JSONP requests missing.

OTHER TIPS

If you look at the specification:

http://www.w3.org/TR/XMLHttpRequest/

You'll see 2 means the headers have been returned already.

const unsigned short **HEADERS_RECEIVED** = 2;

This is essentially the same as jqXHR success. Your browser may vary =)

No seriously.. they will vary, another reason jquery can't support them all and chooses to abstract them:

http://msdn.microsoft.com/library/ie/ms534361.aspx

https://developer.mozilla.org/en-US/docs/Web/API/document.readyState

(couldn't find an authoritative source for chrome)

Actually sounds like you want the function to fire upon the start of the AJAX request.

$("#btn-ajax").ajaxStart(myFunc1);

function myFunc1() {
   $("#message").html("I don't really care if the ajax call succeeds.");
}

I think you want to use the beforeSend option.

see http://api.jquery.com/jQuery.ajax/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top