Skip to content Skip to sidebar Skip to footer

Submit Form With Ajax But Redirect To Another Page

What should I use in the html and in the jquery if I want upon form submit to (a) execute a certain php file (url-a); (b) redirect to another one.(url-b) I currently implemented th

Solution 1:

$('#form').ajaxForm(function() { 
  $.post("url-a.php", {a: a, b: b});
  window.location.href="/url-b.php";
});

Solution 2:

if you want the page to redirect then why do you want it to submit ajaxly any how in the success handler you can redirect to the page

 $.post("url-a.php", {a: a, b: b},function(){
   window.location.href="/page/to/redirect.php";
 });

Solution 3:

in the "complete" function of $.post(..) you should change the location of the browser. You can't use a server-side redirect with ajax.

 $.post("url-a.php", {a: a, b: b},function(){
      window.location.href="/url-b.php";
 });

If you want to redirect before the ajax has completed, that's possible, but hard. I don't know how to do it in PHP, for example. The thing is, if you redirect immediately (again should be done via javascript), then the request is aborted from the client. And if the request is aborted, the server aborts it too. Sometimes it is possible to start a new thread on the server that is separate from the request thread, but if the request is aborted before it fully reaches the server, it will all fail.

In general, you should not do this - it's a wrong approach. Either don't redirect, or don't start the ajax request on the previous page - start it as soon as the new page loads.

Update: I saw you need your ajax request to run for an hour - that won't happen - the browser will timeout. After you confirm that one hour is really needed, check this for asynchronous php tasks. You can start it from $(document).ready(function() {..}); of the 2nd page

Post a Comment for "Submit Form With Ajax But Redirect To Another Page"