开发者

Method to call JavaScript AJAX function on page leave

开发者 https://www.devze.com 2023-03-02 18:13 出处:网络
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 w

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... 
    });
0

精彩评论

暂无评论...
验证码 换一张
取 消