Search code examples
javascriptjsonxmlhttprequest

Writing to HTML id from XMLHttpRequest function


I'm struggling with JSON at the moment, I managed to send a request to php with this Javascript code, but I can only get the result to write to an alert event.

I want to write the JSON to a HTML id, but where can I add the XXX.innerHTML = "MY OUTPUT"?

Thanks a lot, folks. Here is my code.

type

<script>

window.addEventListener("load", () => {
  function sendData() {
    const XHR = new XMLHttpRequest();

    // Bind the FormData object and the form element
    const FD = new FormData(form);

    // Define what happens on successful data submission
    XHR.addEventListener("load", (event) => {
      alert(event.target.responseText);
    });

    // Define what happens in case of error
    XHR.addEventListener("error", (event) => {
      alert("Oops! Something went wrong.");
    });

    // Set up our request
    XHR.open("POST", "server.php");

    // The data sent is what the user provided in the form
    XHR.send(FD);
  }

  // Get the form element
  const form = document.getElementById("myForm");

  // Add 'submit' event handler
  form.addEventListener("submit", (event) => {
    event.preventDefault();

    sendData();
  });
});
</script>

 here

I am having trouble with this part:

type// Define what happens on successful data submission
    XHR.addEventListener("load", (event) => {
      alert(event.target.responseText);
    }); here

Solution

  • If you have element with id="container" then try the following:

    XHR.addEventListener("load", (event) => {
      const response = JSON.parse(event.target.responseText);
      const container = document.getElementById("container");
    
      //display the JSON response in the container
      container.innerHTML = JSON.stringify(response, null, 2);
    });