views:

180

answers:

3

I have a script that does a jquery AJAX post and then should redirect to a different page. The problem is that it is sometimes redirecting before the post completes. There seems to be a couple of solutions but I can't get any of them to work. Thanks for your help! Here is my code:

$.post("cart.php", { 'products[]':postvalues }, function(data) { });
location.href="index.php";
+4  A: 

You need to put your location.href inside the callback function.

$.post("cart.php", { 'products[]':postvalues }, function(data, status) {
    // if you don't want to redirect if it doesn't work, you can check if status == 'success'
    location.href = "index.php";
});

See the jQuery.post docs for more information.

Although, I must ask: if you are going to redirect anyway, why do this via ajax?

Is there some reason you don't want to simply submit a form the normal way? If not, you should probably go that route instead.

TM
That would be simple, however the post is dynamic and made depending on what the user selects, if the user selects certain items more are added. It does act like a checkboxes but done with images instead.
Scott
I had to change `href` from `.` to `#` yet, to make it work.
dhill
+1  A: 

Do the redirect in the callback function on success:

$.post("cart.php", { 'products[]':postvalues }, function(data, textStatus) {
    if (textStatus == "success") {
        location.href="index.php";
    }
});

See jQuery.post for the other statuses to implement further error handling.

Gumbo
A: 

Your problem is that your location change is not waiting for your post action to complete ... since post uses Ajax it passes on control to the next line once it has sent the request.

To fix this, do this:

$.post("cart.php", { 'products[]':postvalues }, function(data) {
// do stuff with data
location.href="index.php";
 });
Sean Vieira