skip to Main Content

I’m currently refactoring some of my previous code to move away from jQuery’s AJAX function towards XMLHttpRequest in vanilla JS. From my understanding, the following code blocks should be identical. However, while the jQuery version works, XMLHttpRequest doesn’t. If successful, you should see an array returned by PHP in the network tab in dev tools.

jQuery

$("#submit").click(() => {
  $.ajax({
    type: "POST",
    url: "http://arig.asuscomm.com/mn/PHP/submitNames.php",
    data: {
      first: "Hi!"
    }
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="submit">
Submit
</button>

Vanilla JS

function send() {
  var data = {
    "first": "Hi!"
  };
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "http://arig.asuscomm.com/mn/PHP/submitNames.php", true);
  xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
  xhr.send(JSON.stringify(data))
}
<button id="submit" onclick="send()">
Submit
</button>

Note that my server is running locally, but I will try to keep it up until my question is answered. And, because my server doesn’t have HTTPS quite yet, you might need to send the request from an HTTP source. Thanks!!!

Edit: I’m using code found here.

2

Answers


  1. jQuery encodes data using the application/x-www-form-urlencoded data format, not JSON.

    You can encode data in that format using the URLSearchParams object.

    const data = {
      "first": "Hi!"
    };
    
    const params = new URLSearchParams();
    Object.entries(data).forEach(
      ([key, value]) => params.append(key, value)
    );
    const encoded_data = params.toString();
    
    console.log(encoded_data);
    Login or Signup to reply.
  2. Problem is with your server not the data itself as I’m getting the response (it’s just an empty array)
    You can either use the same method for sending data like with ajax and use form-data for which I’m getting the same response as with Ajax

    function send() {
      var formData = new FormData();
      formData.append("first", "Hi!");
      var xhr = new XMLHttpRequest();
      xhr.open("POST", "http://arig.asuscomm.com/mn/PHP/submitNames.php", true);
      xhr.send(formData)
    }
    

    Or you will need to handle json input on your server

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search