0

Example code:

        $.ajax({
                url: someUrl,
                data: someData,
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function () { },
        });                

        window.location = urlToGoTo;

Lets say the above code runs when the user clicks a button.

Since the ajax call is asynchronous, what will happen when code such the above runs ? Using a tool like Fiddler, it looks like sometimes the ajax call succeeds, and sometimes it never gets called (i.e. the current web page is changed before the ajax call gets a chance to run).

In cases like this, should you always wait for the ajax call to complete before setting window.location (e.g. in the ajax "complete" event) ?

Just trying to get some insight into what is happening under the hood.

Moe Sisko
  • 11,665
  • 8
  • 50
  • 80

2 Answers2

3

You can do the redirect in the success callback

$.ajax({
    url: someUrl,
    data: someData,
    dataType: "json",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    success: function () {
        window.location = urlToGoTo;
    }
});
Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

You must include the redirection link code inside the ajax call, especially, inside the success function:

 $.ajax({
                url: someUrl,
                data: someData,
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function () { 
                window.location = urlToGoTo;
                },
                error:function(){
                alert("Error Occurred!"); 
                }
        });