I have a normal HTML form in which it is supposed to prevent default form submit and post the values by Ajax. It is not working with my setup Please help me where I went wr
Is your page refreshing when you submit the form even with preventDefault()
?
#
in the action attribute and remove method
.Modify your JS code
var frm = $('#contactForm1');
frm.submit(function (ev) {
ev.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
});
Put preventDefault
before your ajax fires. Whats happening on your code is, your form is being executed with the action and method supplied in HTML, therefore your JS cannot catch it.
$('#submit').click(function(e){
//call ajax
e.preventDefault();
})
set the submit button as type="button"
instead of type="submit"
,
and let's say the submit button has id submit-button
. you can submit the form in javascript like this:
$("#submit-button").click(function(){
//send ajax
})
Wrap your code in DOM Ready
$(function () {
var frm = $('#contactForm1');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
});