Skip to content

Instantly share code, notes, and snippets.

@ttamg
Created May 26, 2019 18:00
Show Gist options
  • Save ttamg/431f73858d44acf206e603c71ab941f3 to your computer and use it in GitHub Desktop.
Save ttamg/431f73858d44acf206e603c71ab941f3 to your computer and use it in GitHub Desktop.
Post the Django form by AJAX and post messages as required
// Parameters ...
// Note this should be run AFTER the form has been loaded in order for the JS to attach to the form
// Trigger: Submission of the form
// Form: must have the class 'submitByAJAX' for this to work
// URL: fetched from the ajax-url attribute on the form object
$(".submitByAJAX").each(function () {
var form = $(this).find('form');
form.submit(function (e) {
e.preventDefault();
var dataURL = form.parent().attr("ajax-url");
var modalID = form.parent().attr("modal-id");
var button = form.find(':submit')
button.attr("disabled", true);
$.ajax({
url: dataURL,
type: "POST",
// dataType: 'html',
data: form.serialize(),
success: function (data, textStatus, XHR) {
// console.log(XHR.status + ": " + textStatus);
if (XHR.status == 200) {
$('#' + modalID).modal('hide')
$('#' + modalID + 'Content').empty();
postSuccessMessage('Your response has been saved.');
//var surveyChart = refreshChart();
//location.reload();
needsRefresh();
} else {
// console.log(data);
$('#' + modalID + 'Content').empty();
$('#' + modalID + 'Content').append(data);
};
},
error: function (XHR, textStatus, textError) {
// console.log(XHR.status + ": " + XHR.responseJSON);
postErrorMessage('There is an error - please check and retry.')
$('#' + modalID).modal('hide')
$('#' + modalID + 'Content').empty();
},
complete: function () {
button.attr("disabled", false);
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment