I'm trying to implement my form for the following two actions after it is submitted:
- the form action is called and the data is sent to a database
- also send this form data to another php file using jquery ajax
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.