So I'm trying to POST to my server (php) from Javascript and am trying to not use JQuery.
This code works and posts the necessary data to the database
var msg = {};
msg['name'] = 'joe';
msg['message'] = 'why no work';
$.post(phpURL, msg, function(data) {});
but this one does not
var xhr = new XMLHttpRequest();
xhr.open("POST", phpURL, true);
xhr.send(msg);
I even looked at my php logs, looked at the headers and the only difference of the JQuery one from the XHR one I could see was the content-type header "application/x-www-form-urlencoded; charset=UTF-8"
and this header "x-requested-with" "XMLHttpRequest"
.
So I tried all combinations of the following headers.
var xhr = new XMLHttpRequest();
xhr.open("POST", phpURL, true);
//xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
//xhr.setRequestHeader('x-requested-with', 'XMLHttpRequest');
xhr.send(msg);
to no effect.
It is worth mentioning if I try to add JSON.stringify(msg)
anywhere, it does not work, neither in JQuery or XHR. But I would like to get this working first, and explain this bizarre difference.
I am inclined to believe this is a Javascript issue since the JQuery post works and in addition, a GET request of the server and the same table I'm trying to post to does work.