简体   繁体   中英

jQuery AJAX POST to PHP works, XMLHttpRequest doesn't

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 .

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM