
Question:
I have a form and when the user clicks the submit button I want to run a separate PHP script before the form-action (going to the next page) gets executed.
Of course I can stop the form-action with evt.preventDefault();
and then I can fire my jquery $.post
call but then I cannot 'resume' or undo this preventDefault call, as far as I can see.
So what is the best way to execute a script that process some information after a user clicks the submit button BUT before the user gets redirected to the next page defined in the form action tag?
(Of course I could just carry over the data and perform whatever I want on the next page – but in this case, I would like to keep it separate).
Thanks for any suggestions!
Answer1:You can try something like this:
var posted = false;
$('form').on('submit', function(ev) {
if ( ! posted ) {
ev.preventDefault();
$.post(url).done(function() {
posted = true;
$('form').trigger('submit');
});
}
posted = false;
});
Or more succinct, using <a href="http://api.jquery.com/trigger/#example-3" rel="nofollow">extra parameters</a>:
$('form').on('submit', function(ev, posted) {
if ( ! posted ) {
ev.preventDefault();
$.post(url).done(function() {
$('form').trigger('submit', [true]);
});
}
});
Answer2:<ol><li>
Your $.post call can be run synchronously, so the form would not submit until you've got a response from the server.
</li> <li>You can submit the form programmatically, perhaps in your callback function.
</li> </ol>Answer3:prevent default on form
, then run post
, on success of post
, target the form by id and use .submit();
$('#submit-button').click(function(e) {
e.preventDefault();
$.post({
url:'url',
success:function() {
$('#formid').submit()
}
});
});
Answer4:<ol><li>Go head with your evt.preventDefault().</li> <li>Make an $.ajax() call to run your php script.</li> <li>In the $.ajax() success/failure callback, check the output of the php script you want to run, and accordingly make a $.post call (or not).</li> </ol>
Answer5:You can always hook the click event, and do your stuff. When you are done you just do $(form).submit();
<a href="http://jsfiddle.net/DNTYg/" rel="nofollow">Working example</a>
$("#submitbutton").click(function(e) {
e.preventDefault();
// do your ajax stuff here.. $.post().
$("#form").submit();
});
Answer6:You can use just use the native submit function instead of jQuery's submit() which goes through the event handler again
$('form').submit(function(e){ // change form to your form id
e.preventDefault();
var el = this; // store this form in variable
$.post('/echo/html/',data,function(d){ // your post function
el.submit(); // trigger native submit function in success callback
});
});
<a href="http://jsfiddle.net/5vEsu/" rel="nofollow">FIDDLE</a>
Answer7:In your form tag, add onsubmit="myfunction()"