Hello to all! I am writing my simple function to send data from a form without reloading the page, but a problem has arisen: after sending the data via XMLHttpRequest, the page still reloads (sends the form with a get request). In this case, the server receives the data from the form, processes it and issues the appropriate response.
The form:
<form id="reg-form" onsubmit="sendForm(this.id, 'handler-url')> <input type="text" name="data"> <button>Send</button> Handler:
var sendForm = function (formId, url) { 'use strict'; var form = document.getElementById(formId); var formData = new FormData(form); var xhr = new XMLHttpRequest(); // При установке этого заголовка работа функции прекращается ошибкой // xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.open("POST", url, true); xhr.send(formData); if (xhr.status == 200) { alert("Worked!"); } else { alert(xhr.status + ': ' + xhr.statusText+ 'Error'); } } The server responds with "OK", or if the sent data is entered incorrectly, sends json with a description of the errors. But in any case, I receive in the alert: "0: Error" and after that the form is sent get-ohm.
Please help me: how to make sure that the form is not sent get-ohm after XHR, and why can not I get a response from the server 200, although it sends it?