The website has a blog page with a search field and category checkboxes. Searching for something or checking/unchecking a category starts an AJAX request to get the posts based on the search/categories, then populates those results into the list on the page.
Currently this functionality works with jQuery, but my attempts to write it in plain JS are failing with 400 errors.
Here is the jQuery for this that works:
$.ajax({
url: Knuckle.ajaxurl,
type: 'post',
dataType : 'json',
data: {
action: 'kp_filters',
nonce: Knuckle.nonce,
form: serialized_form,
base_url: base_url
},
success: function( response ){
// console.log('===== SUCCESS =====');
// console.log(response);
if( response.results && response.results.length ){
$('.results-item').remove();
$('.results-pagination').remove();
for(i=0; i<response.results.length; i++){
$('.results-list').append( response.results[i] );
}
if( response.pagination && response.pagination.length ){
$('.results-inner').append( response.pagination );
}
} else {
// No results.
$('.results-item').remove();
$('.results-pagination').remove();
}
},
error: function( response ){
// console.log('===== ERROR =====');
// console.log(response);
},
complete: function( response ){
// console.log('===== COMPLETE =====');
// console.log(response);
// Remove the loading indicator
$('.sk-circle').removeClass('is-loading');
}
});
Here's the plain Javascript version of the above snippet, which is getting the 400 errors:
var serialized_form = encodeURI( kp_serialize(window.mirrored_params) );
var base_url = kp_get_base_url();
var data = {
url: Knuckle.ajaxurl,
type: 'post',
dataType : 'json',
action: 'kp_filters',
nonce: Knuckle.nonce,
form: serialized_form,
base_url: base_url
};
console.log('About to post this data: ');
console.log(data);
var xhr = new XMLHttpRequest();
xhr.open('post', Knuckle.ajaxurl);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onreadystatechange = function() {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if( xhr.readyState === DONE ){
console.log('ajax is done: ' + xhr.status);
if( xhr.status === OK ){
console.log(xhr.responseText); // 'This is the returned text.'
}
} else {
console.log('Error: ' + xhr.status); // An error occurred during the request.
}
};
xhr.send(data);
Here's a screenshot of what I get in the console: https://i.sstatic.net/z3F6u.jpg
I've been messing with the data and trying different headers for my XMLHttpRequest, but it always comes back with a 400. Tried disabling plugins that might have an effect on it, but nothing there either.
What am I doing wrong with the plain JS AJAX? What is jQuery doing that my code isn't?
data
to astring
, i.e.:data = 'action=kp_filters&nonce=' + Knuckle.nonce + '&form=' + serialized_form + '&base_url=' + base_url;
. And secondly, the request header should beapplication/x-www-form-urlencoded
. See this and this.