So I have what should be a pretty easy problem that I can't seem to figure out and I'm too embarrassed to go to SO so here I am.
Previously I did/was doing a jQuery AJAX POST of an object to a php file and everything worked just fine. Code looks like:
Code:
$('#retrieve-button').on('click', function() {
var filterdata = {
filter: $('#type-filter').val() // this is "All"
};
$.ajax({
url: '../scripts/get-data.php',
type: 'POST',
dataType: 'json',
data: filterdata,
success: function(data) {
// do stuff
},
error: function(xhr, textStatus, errorThrown) {
console.log('ajax error');
}
});
});
and on the PHP side it just took $_POST['filter'] and everything worked just fine.
Now I'm trying to rewrite this without jQuery (because I'm a masochist or something) and here's what I came up with:
Code:
document.getElementById('retrieve-button').addEventListener('click', function () {
var filterdata = {
filter: document.getElementById('type-filter').value
};
var retrieveResults = new XMLHttpRequest();
retrieveResults.onreadystatechange = appendResults;
retrieveResults.open('POST', '../scripts/get-data.php', true);
retrieveResults.setRequestHeader("Content-type","application/x-www-form-urlencoded");
retrieveResults.send(JSON.stringify(filterdata));
function appendResults () {
if (retrieveResults.readyState === 4 && retrieveResults.status === 200) {
// do stuff
}
}
});
The problem is the non-jQuery thing being sent isn't the same as the jQuery one. jQuery turns that object into a string that is "filter=All" which obviously isn't the same as the JSON.stringified version. Where/what is jQuery doing? How do I replicate that without it? Is this a header issue or something? I'm pretty confused here and looking at a ton of SO questions didn't even come close to answering it.