I can submit a form like this and it works:
$(document).on('click', '#someLink', function() {
var frm = $('#myCustomForm');
frm.submit();
});
However, when I submit the same form like below, the form is not being submitted:
$(document).on('click', '#someLink', function() {
var frm = $('#myCustomForm');
frm.submit(function(e) {
$.ajax({
type: 'POST',
url: '/comments/new/',
dataType: 'application/json',
data: frm.serialize(),
success: function(data) {
alert('successful');
},
error: function(data) {
alert('something went wrong');
}
});
e.preventDefault();
return false;
});
});
What am I doing wrong here?
The two codes are complete opposites. frm.submit(function(e) {}) assigns a function to the form submission so you would need to submit the form again.
You just want to run the Ajax code so just run the code.
$(document).on('click', '#someLink', function(e) {
var frm = $('#myCustomForm');
$.ajax({
...
});
e.preventDefault();
});
You can attach your event handlers when the document
is ready. Plus, return false;
is enough for your submit
handler.
$(document).ready(function() {
var frm = $('#myCustomForm');
frm.on('submit', function() {
$.ajax({
type: 'POST',
url: '/comments/new/',
dataType: 'application/json',
data: frm.serialize(),
success: function(data) {
alert('successful');
},
error: function(data) {
alert('something went wrong');
}
});
return false;
});
});
UPDATE
I think you should take a careful look at your url /comments/new/
to make sure it's correct. Better still, simply get the action
attribute of your form as the url instead.
url: frm.attr('action'),
Change that and see if it works.