I have two really simple form that looks like this:
<form name='a' id='a'> // form a
<input type="text" name="x" id="x"> //input 1
<input type="text" name="y" id="y"> //input 2
<button>submit</button>
</form>
when the form a is submitted, the URL query string will look like example.com/?x=1&y=2
<form name='b' id='b' method="POST"> //form b
<input type="hidden" name="sum" id="sum"> // hidden input sum
</form>
I have a computation script code that calculates the sum of input 1 and input 2 then stores the sum to hidden "input sum" inside "form b"
<script>
window.addEventListener("DOMContentLoaded", function(){
function calculate(){
// I want it also to work when someone paste the url example.com/?x=1&y=2
const urlParams = new URLSearchParams(window.location.search);
x = urlParams.get('x')
y = urlParams.get('y')
sum = parseInt(x)+parseInt(y)
document.getElementById('sum').value = sum //store sum to hidden input
}
calculate()
});
</script>
How do I send value of hidden "input sum" to the backend(Django) when someone submits form a or paste the URL?
I prefer something like this if such thing is viable:
if sum.value not empty:
form_b.submit()
form_b.prevent_page_refresh
I don't know if this is possible or how to implement such in js or ajax, if not I'm open to all ideas.
Edit: Ajax solution right after def function calculate(){...}, And removed the 2nd form:
$.ajax({
type:'POST',
url:'{% url "index"%}',
headers: {
'X-CSRFToken': '{{ csrf_token }}'
},
data:{
sum:sum,
},
success: function(){}});
xandyas query parameters, why not just calculate the "sum" in the backend itself at that time?