Created
May 26, 2019 18:00
-
-
Save ttamg/431f73858d44acf206e603c71ab941f3 to your computer and use it in GitHub Desktop.
Post the Django form by AJAX and post messages as required
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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