title: Make HTTP request to web API using regular JavaScript
body: <p>I am trying to access a php script on a server that returns a JSON object. I am trying to do this with pure JS (not jQuery or React). </p>
  
  <p>I have the following JS:</p>
  
  <pre><code>//Define Parameters:
  var param1 = document.getElementById("param1");
  var param2 = document.getElementById("param2");
  
  //Send data to the server:
  function sendData() {
  
      var XHR = new XMLHttpRequest();
  
      //On Success:
      XHR.addEventListener("load", function(event) {
          alert(event.target.responseText);
      });
  
      //On Fail:
      XHR.addEventListener("error", function(event) {
          alert('Oops! Something went wrong.');
      });
  
      //Setup the request:
      XHR.open("POST", "https://www.example.com/folder/file.php");
      XHR.setRequestHeader('Content-Type', 'application/json');
  
      //Perform the request:
      XHR.send(JSON.stringify({
          param1: param1,
          param2: param2
      }));
  
  }
  </code></pre>
  
  <p>These parameters are inputted from a HTML page by the user. It seams that the request is not sending to POST parameters and the <code>request type</code> is <code>OPTIONS</code> not <code>POST</code>.</p>
  
  <p><strong>EDIT 1:</strong></p>
  
  <p>As suggested in the comments, I have tried a fetch request and the request is working. It does not appear to be passing my POST parameters through. My code is as follows.</p>
  
  <pre><code>//Define Parameters:
  var param1 = document.getElementById("param1");
  var param2 = document.getElementById("param2");
  
  var formData = new FormData(document.getElementById('form'));
  formData.append('param1', param1);
  formData.append('param2', param2);
  
  //Send data to the server:
  function sendData() {
  
      var url = 'https://www.example.com/folder/file.php';
  
      fetch(url, {
      method: 'POST',
      body: formData,
      headers:{
          'Accept': 'application/json',
          'Content-Type': 'multipart/form-data'
      }
      }).then(res =&gt; res.json())
      .then(response =&gt; console.log('Success:', JSON.stringify(response)))
      .catch(error =&gt; console.error('Error:', error));
  
  }
  </code></pre>