Reputation: 69
I'm trying to implement my form for the following two actions after it is submitted:
It's like performing two actions using a single button, single form
Here's my code:
tryform.php:
$(document).ready(function() {
$("#parentForm").submit(function(e){
e.preventDefault();
if (!$('.formSubmitButton').hasClass('submitted'))
{
// disable the form to prevent multple clicks
$('.formSubmitButton').addClass('submitted');
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
type: "POST",
url: "postdata.php",
data: serializedData
});
request.done(function(data){
$('.parentForm').submit();
// enable the form
$('.formSubmitButton').removeClass('submitted');
console.log("Working");
});
request.fail(function(){
console.error("Error occured");
});
}
return false;
});
});
<!--My Form-->
<form id="parentForm" action="thanks.php">
First Name:<input type="text" id="firstName" name="firstName"/>
<br/>Last Name:<input type="text" id="lastName" name="lastName"/>
<br/><input type="submit" id="formSubmitButton" value="submit" />
</form>
postdata.php:
$firstname = $_POST['firstName'];
$lastname = $_POST['lastName'];
$lastname1 = $lastname . " from postdata";
//$test_query = "INSERT INTO testuser (firstname, lastname) VALUES ('" . $firstname . "', '" . $lastname . "')";
$test_query1 = "INSERT INTO testuser (firstname, lastname) VALUES ('" . $firstname . "', '" . $lastname1 . "')";
$result_test1 = mysql_query($test_query1) or die(mysql_error());
thanks.php:
$firstname = $_POST['firstName'];
$lastname = $_POST['lastName'];
$test_query = "INSERT INTO testuser (firstname, lastname) VALUES ('" . $firstname . "', '" . $lastname . "')";
echo $test_query;
$result_test = mysql_query($test_query) or die(mysql_error());
I've used same insert sql statements for now. The form data is being inserted from postdata.php (using jQuery ajax) but NOT thanks.php (using form action). Ideally, I would like to have both of them to work.
Upvotes: 0
Views: 1451
Reputation: 95022
The second call to $('.parentForm').submit()
does nothing because you prevented the default action and returned false. (and because the form has an id, not a class!)
To avoid this, use the form's submit method rather than triggering the submit event again.
$('#parentForm')[0].submit();
this will cause the form to submit without triggering any submit event handlers.
(you can now get rid of your submitted class and if statement)
Alternatively, simply move your e.preventDefault
inside the if statement and remove the return false
.
Upvotes: 2