ekeren
ekeren

Reputation: 3458

How can I send an ajax request and redirect to another page

I have seen the following sequence in my client code:

$.ajax({
    url: "...",
    data: {},
    success: function() {
    // I don't care about the response
    }
});

top.location.href="http://...." 

As you can see the browser send an ajax request, and doesn't care about the response. after it sends the request the page is redirected to another url using the top.location.href statement .

I am a newbie in javascript and I am not sure if the ajax request is guaranteed to be sent?

Is there another approach to get this send and forget and redirect ajax behavior?

EDIT:

Just to clarify, I do not want to wait for this ajax to finish it's long operation and put the redirection line in the success callback.

Upvotes: 0

Views: 1426

Answers (2)

Piyush Sardana
Piyush Sardana

Reputation: 1758

if you just want to redirect to some other page after ajax request is successful then why dont you put your top.location in success function or if you just want to redirect regardless your ajax is succeeded or not...write your top.location in a function of complete parameter.

Upvotes: 1

Justin Ethier
Justin Ethier

Reputation: 134157

If you want to be 100% sure that the message was received and processed, you should do your redirect in the success handler.

This would also enable you to do error handling if that is required - for example, what if you make the AJAX request but it fails for some reason? If you just redirect the user would never know there was a problem. But maybe you do not need to care about this depending upon this specifics of your application.

Upvotes: 2

Related Questions