I am sending some form data with an XMLHttpRequest
let xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
try {
let data = JSON.stringify(sendForm);
xhr.send(data);
alert(xhr.status);
}
catch (error) {
alert(error);
}
This works as it will go into this after the alert pops up in the browser
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
location.href = 'thanks.html';
}
and data will be inserted into the database as expected. However, if I comment out the alert after the xhr.send(data);
this code will no longer inserts data into the database or display the correct page, it just displays the js file. If I set a break point at xhr.send(data)
when I step past it is when the js file is displayed.
Any thoughts as to why the data is being sent if I include the alert(xhr.status)
step in the code but not when I comment it out? Also, any thoughts why the try{}catch{}
is not catching the error? Thanks I am not very familiar with javascript right now.