When the jquery $.post doesn't work the way you expect it to...

When the jquery $.post doesn’t work the way you expect it to…

The Problem

In my was posting a contact form to an outside service, and then redirecting to a page on the same site.  I thought, Aha, I will use the handy jquery .post command – it looked something like this.

$.post(“https://www.outsidesite.com/FormSubmit.php”, $(“#myform”).serialize());

But curiously, half of the time I filled out the form the data did not reach the outside server, and the other half the redirect did not happen.

The Cause

$.post is an asynchronous operation by definition – and cannot be made synchronous.

The Solution

Just use the regular jquery .ajax function, and set async to false

$.ajax({type: ‘POST’, url: “https://www.outsidesite.com/FormSubmit.php”, data: $(“#myform”).serialize(),async:false});

That’s it, now the browser waits until the submission is complete and everything works as expected.



Written By Steve French


Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.