1

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
JimmyBoys
  • 11
  • 1
  • How are you triggering the XHR? – Barmar Sep 16 '21 at 21:14
  • The code that's calling this is probably reloading the page. The alert delays that so you get the response from the AJAX and do the redirect. – Barmar Sep 16 '21 at 21:16
  • Is it being called from a submit button? You probably forgot to prevent the default form submission. – Barmar Sep 16 '21 at 21:18
  • Yes, Barmar the js and xhr is called with a submit button, where should I prevent the default form submission? – JimmyBoys Sep 16 '21 at 21:29
  • Does this answer your question? [How to prevent default on form submit?](https://stackoverflow.com/questions/17709140/how-to-prevent-default-on-form-submit) – Christopher Sep 16 '21 at 22:24
  • @Christopher is there another way? if i do function SubmitForm() {preventDefault()...} that doesn't seem to be working – JimmyBoys Sep 16 '21 at 23:00
  • You have to call the `event.preventDefault()` function of the event submitted during the onsubmit call. `onsubmit="function(event) { event.preventDefault(); }"` – Christopher Sep 16 '21 at 23:04
  • Add your actual code and we can show more specifically how to fix it. – Barmar Sep 17 '21 at 01:44
  • Got it figured out between @Barmar and Christopher thank you guys!! – JimmyBoys Sep 17 '21 at 03:53

0 Answers0