ajax inside to submit form code example
Example 1: jQuery AJAX form submit
// jQuery ajax form submit example, runs when form is submitted
$("#myFormID").submit(function(e) {
e.preventDefault(); // prevent actual form submit
var form = $(this);
var url = form.attr('action'); //get submit url [replace url here if desired]
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes form input
success: function(data){
console.log(data);
}
});
});
Example 2: Sending an Ajax request before form submit
$('form').submit(function(e) {
// this code prevents form from actually being submitted
e.preventDefault();
e.returnValue = false;
// some validation code here: if valid, add podkres1 class
if ($('input.podkres1').length > 0) {
// do nothing
} else {
var $form = $(this);
// this is the important part. you want to submit
// the form but only after the ajax call is completed
$.ajax({
type: 'post',
url: someUrl,
context: $form, // context will be "this" in your handlers
success: function() { // your success handler
},
error: function() { // your error handler
},
complete: function() {
// make sure that you are no longer handling the submit event; clear handler
this.off('submit');
// actually submit the form
this.submit();
}
});
}
});