call ajax while submit form code example
Example 1: ajax submit form data
$(function() {
$('form.my_form').submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function(data) {
}).fail(function(data) {
});
});
});
Example 2: ajax submit form data
<form id="contactForm1" action="/your_url" method="post">
<!-- Form input fields here (do not forget your name attributes). -->
</form>
<script type="text/javascript">
var frm = $('#contactForm1');
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
});
</script>
Example 3: Sending an Ajax request before form submit
$('form').submit(function(e) {
e.preventDefault();
e.returnValue = false;
if ($('input.podkres1').length > 0) {
} else {
var $form = $(this);
$.ajax({
type: 'post',
url: someUrl,
context: $form,
success: function() {
},
error: function() {
},
complete: function() {
this.off('submit');
this.submit();
}
});
}
});