简体   繁体   中英

Method to call JavaScript AJAX function on page leave

I have a web page with a form, a submit button for that form, and a link that takes a user to another page. I want to upload whatever changes I've made to that form to the server (a PHP script that will save the values) when a user clicks that link to take them to another page.

What is the best event to bind a JavaScript ajax function so that the form gets passed to the server and the user is then redirected to the next page?

One way is to redirect on the server side,
If using php:

header("Location: new_page.php"); //involves no javascript

Another way is to use javascript ajax, i use jQuery:

$('form').submit(function(e){

   e.preventDefault();

   $.ajax(
    {
       url: this.action,
       data: $(this).serialize(),

       success: function(){
            window.location = 'newpage';//redirect on success
       }
    }
   )
})

If you don't mind jQuery,

 $("#yourlink").click(function (event) {
    $.ajax({
      type: "POST",
   url: "some.php",
   data: "name=John&location=Boston",
   });
location.href("your link"); //actually, i'm pretty sure the link will go ahead and fire anyways without this... 
    });

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