I am just starting out with ajax…trying to submit a form with ajax through a post request. For some reason, the code I wrote works exactly every other time. When I first submit the form, it’s processed through ajax. When I submit again, javascript is not called and the form is submitted with a normal post request. When I submit a third time, ajax works again. And so on. Any idea how to fix this to make ajax work every time?
function contact_submit() {
alert('starting');
var data = {
name: $('#id_name').val(),
email: $('#id_email').val(),
title: $('#id_title').val(),
message: $('#id_message').val(),
csrfmiddlewaretoken: $('input[name="csrfmiddlewaretoken"]').val()
};
$('#contact_form').load("/contact/?ajax", data, function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#contact_form").html(msg + xhr.status + " " + xhr.statusText);
}
});
alert('load was performed');
return false;
}
$(document).ready(function () {
//*$(document).submit(contact_submit);
$(document).on("submit","form",contact_submit);
});
Solved it using a workaround. Before, I was regenerating the submit button every time with my ajax request, and I think the event handler wasn’t attached to the regenerated submit element. I moved the submit outside the target of ajax request, and it started working every time.