Why my form is not again submitting to another URL after ajax submit.
with the below script i want to post form with ajax and then submit same form to other url.
first my form will submit to Ajax URL (http://www.mywebsite.com/insertdata.php) and then it same form will submit to form action URL (http://www.example.com/mail.php)
HTML
<form id="contact_form" action="http://www.example.com/mail.php" method="post" novalidate="novalidate" data-track="formSubmit" name="contact_form">
<!------Form Elements ------->
<input class="form-control submit" type="submit" value="Submit">
</form>
JavaScript
$("form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: "http://www.mywebsite.com/insertdata.php",
type: "post",
crossDomain: true,
data: $(this).serialize(),
success: function(responce) {
console.log(responce);
return true;
}
});
});
remove event.preventDefault();
If this method is called, the default action of the event will not be triggered.This is stopping the form to submit to the url in action
attribute.
$("form").on("submit", function(event) {
event.preventDefault();
flag=false;
$.ajax({
url: "http://www.mywebsite.com/insertdata.php",
type: "post",
crossDomain: true,
data: $(this).serialize(),
success: function(responce) {
console.log(responce);
return true;
$("form").off("submit");
$("form").trigger( "submit" )
}
});
});
In success function add a form submit.
$("form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: "http://www.mywebsite.com/insertdata.php",
type: "post",
crossDomain: true,
data: $(this).serialize(),
success: function(responce) {
console.log(responce);
$("form").submit();
return true;
}
});
});
UPdate: Can you use button click, it will work
$(".submit").on("click", function(event) {
$("#contact_form").on("submit", function(event) {
$.ajax({
url: "http://www.mywebsite.com/insertdata.php",
type: "post",
crossDomain: true,
data: $(this).serialize(),
success: function(response) {
console.log(response);
return true;
}
});
});