Prabhu
Prabhu

Reputation: 13335

Will redirecting before an Ajax call returns cause issues?

I have an ajax call where a redirect happens after the call returns (inside the success handler):

$.ajax({
        type: "POST",
        url: "/LoadSomeData",
        dataType: "json",
        success: function (response) {  
            location.href = "http://mysite.com";                
        }
    });

If I do a redirect before the call returns, will the ajax call get cancelled? For example:

 $.ajax({
            type: "POST",
            url: "/LoadSomeData",
            dataType: "json",
            success: function (response) {  
                location.href = "http://mysite.com";                
            }
        });
 location.href = "http://mysite.com";    

I have a situation where I don't really care to wait till all my data is loaded, and I'd like to redirect immediately. Question is will redirecting (possibly before the loading has completed) disrupt the loading process?

Thanks...

Upvotes: 5

Views: 1005

Answers (3)

Majid Fouladpour
Majid Fouladpour

Reputation: 30252

If you redirect outside ajax callbacks, the callbacks will be destroyed and you will redirect immediately. This should have no impact on loading process of the redirected address.

Upvotes: 3

Sören Kampschroer
Sören Kampschroer

Reputation: 358

Not having testet that i would assume that the ajax call will be cancelled. you could try ajax calling a php script containing <?php sleep(10); ?> or something similar and see if the redirect happens immediately or if it takes 10 seconds.

hope that helps ;)

Upvotes: 2

goat
goat

Reputation: 31813

Browsers are under no obligation to wait for ajax requests to complete, and they don't.

Upvotes: 1

Related Questions