简体   繁体   中英

$.post() doesn't work if there's a re-direct after it: window.location.href =

I have a list and when an element from that list is clicked I want to record some info in my database so I'm using the following:

<li class="item"><a href="javascript:addactivity()">Add activity</a></li>

<script>
function addactivity(){

    $.post('update.php');   
    window.location.href = "http://www.mysite.com/page.php";

}
</script>

If I comment out window.location.href = " http://www.mysite.com/page.php "; the database is updated because $.post('update.php'); works properly. If I don't comment out window.location.href = " http://www.mysite.com/page.php "; the database is not updated but the re-direct works to www.mysite.com.

For some reason adding window.location.href = " http://www.mysite.com/page.php "; stops $.post('update.php'); from running. Is there anyway to fix this?

Use the callbacks to manage the situation:

function onSuccess() {
  window.location.href = "http://www.mysite.com/page.php";
}

function onFailure() {
  alert('An error has ocurred while updating database');
}

$.post('update.php').done(onSuccess).fail(onFailure);

Read in the documentation others examples, and why it works:

As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error) methods take a function argument that is called when the request terminates.

This talks about $.get, but the same works for $.post.

Use the success method that will wait until the post completes before it does a redirect

$.post('update.php', function(){
    window.location.href = "http://www.mysite.com/page.php";
});

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