Reputation: 337
Could anyone show me how to submit a form over two pages where, if the form is closed on the second page this will still automatically submit the first page's info?
E.g.
Page 1: Full Name Email Phone Number
User clicks submit...
Page 2: Thanks for submitting your details please select a call back time..
The user would then either close the window or enter a call back time and press submit but I would need the original info to be submitted even if they close the window on the second page and do not enter a call back time.
I was thinking maybe of maybe using session variables to store the info then possibly javascript/jquery to submit the form if the window was closed?
Could anyone suggest the best was to do this?
I should probably mention as well I am inserting the data into a MySQL table then posting the data using CURL. So I could quite easily insert into the database then just do an update statement on the last id if the call back time is submitted.
But I don't know how to post the last MySQL record if the window is closed on the second form page?
Upvotes: 0
Views: 1904
Reputation: 13994
You can't really.
$(window).bind('beforeunload', function() {
// Do submit here
});
Might seem to work, but
a) regular form submits (i.e. redirects to another page with POST or GET) are not allowed during the beforeunload phase, so will not work.
b) AJAX form submits will fire, but you are never sure they will arrive, because the browser will not wait for the callback to happen, but will simply close the window after your code has run.
Upvotes: 0
Reputation: 13785
The beforeunload
event fires whenever the user leaves your page for any reason.
For example, it will be fired if the user submits a form, clicks a link, closes the window (or tab), or goes to a new page using the address bar, search box, or a bookmark.
You could exclude form submissions and hyperlinks (except from other frames) with the following code:
var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });
$(window).bind("beforeunload", function() {
return inFormOrLink || confirm("Do you really want to close?");
})
The live
method doesn't work with the submit event, so if you add a new form, you'll need to bind the handler to it as well.
Note that if a different event handler cancels the submit or navigation, you will lose the confirmation prompt if the window is actually closed later. You could fix that by recording the time in the submit
and click
events, and checking if the beforeunload
happens more than a couple of seconds later.
Upvotes: 1
Reputation: 1979
$(window).bind('beforeunload', function() {
$("#form-submit").click();
});
where #form-submit is the ID of your submit-button.
Upvotes: 1