My website has a <form>
that is usually submitted using a submit
button:
<form action='/doit' method='post'>
<input type='text' name='ex1_q1' value='AAA'>
<input type='text' name='ex2_q1' value='BVB'>
<input type='submit' value='Go'>
</form>
This functionality works as intended.
Now, I want to automatically send the form data every 10 seconds using AJAX without refreshing the page. However, when implementing this:
setInterval(function() {
var fd = new FormData(document.querySelector('form'));
fd.append("dt", +new Date);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/doit");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(fd);
}, 10 * 1000);
The data is sent successfully, but the server receives it in a different format compared to when using the "Submit" button.
Specifically:
With Ajax/XHR, the body of the request looks like:
b'------WebKitFormBoundaryQb7yIKHLZODhAjqI\r\nContent-Disposition: form-data; name="ex1_q1"\r\n\r\nAAA\r\n------WebK
When using the Submit button, I receive:
b'ex1_q1=AAA&ex2_q1=BVB&accept=on&numero=1'
which is the desired format for all cases.
Question: How can I ensure that data sent with an XHR request follows the same format as when using a Submit button (as described in case 2.)?