简体   繁体   中英

jQuery ajax/post request with a change of page not working

Now the problem below happens only with Safari. Chrome, Opera, IE all work fine. I have tried:

function do(x){
    $.ajax({url: "next.php",
    type: "POST",
    data: {'cand': x},
    success: leave()});
}
function leave(){window.location = "next.php";}

This:

    $.post("next.php", {'cand': x});
    window.location = "next.php";

And the other two combinations of the above as well. I noticed that when I don't leave the page, the ajax/post request both work, but when I leave the page, they dont. What I mean is when I use the window.location command. As in, the user will leave the page but the post request will not work. Again, this only happens in Safari. I dont't have a Safari browser immediately in front of me so I cannot test it thoroughly.

Can anyone who has any clue let me know what's going on?

If you do this: success: leave() (as in your first example) then you evaluate leave function immediately, and the change of location occurs concurrently to the ajax call. Some browsers will complete the ajax call, some won't.

Instead, do this: success: leave . This will call leave function after the ajax call.

You could try the following, because here the function() is only called after the PHP execution is completed. In your case, it could be that the callback is executed before the Ajax is completed. In that case you could maybe use a little work around and use setTimeout() to wait a short time before leaving.

$.post('next.php', {cand: x}, function() {
    // Callback function: called after php script is completed
    // setTimeout waits 500ms before leaving
    setTimeout(function(){
        leave();
    }, 500);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM