The issue to attack was the fact that it doesn't matter what fancy javascript we put in place because once we hit submit, the form's default code will kick in and it will try to redirect us. so first, we have to suppress the default action of the form. I did that with the following javascript. (all this code runs when the document is ready.)
$("form").on("submit", function (e) {
e.preventDefault();
}
e.preventDefault();
}
This was okay because we only have one form on this page. I could have also changed "form" to be the exact id or class of my house list form but I figured it was un-necessary.
Now that this is done and the form will now lie here inactive, we need to send the input to the view ourselves but we also want to do this sort-of in the background. We don't really need feedback from this action as all feedback is already handled. To do this, I used ajax.
So, in order to set up this ajax call, we need to collect the information that would have been sent as the form was submitted. It also needs to be in the same format. I searched for a way to do this and quickly found jquery's "serialize" function. It gets all that data and prepares it to be sent. The only other thing I need is the url to send the data to which we have from the action of the original form.
The code looked like this:
$.ajax({
type: "POST",
url: "{% url 'management:submitChange' %}",
data: $("#houseForm").serialize(),
})
type: "POST",
url: "{% url 'management:submitChange' %}",
data: $("#houseForm").serialize(),
})
And finally, we need to put both of these code sections together so they run immediately when the page loads. Then the ajax call needs to run on the form's attempt to submit. The finished code looked like this:
$(document).ready(function() {
$("form").on("submit", function (e) {
e.preventDefault();
if (true){
console.log($("#houseForm").serialize())
$.ajax({
type: "POST",
url: "{% url 'management:submitChange' %}",
data: $("#houseForm").serialize()
})
}})})
e.preventDefault();
if (true){
console.log($("#houseForm").serialize())
$.ajax({
type: "POST",
url: "{% url 'management:submitChange' %}",
data: $("#houseForm").serialize()
})
}})})
I threw in that console.log() for debugging purposes and it is not necessary.
And with that, you have a form that does not refresh the page every time you change a light!
Ahh, the power of Ajax!