Sending WordPress object via AJAX with pure Javascript


Staff member
I'm working in WordPress and I'm trying to replace my jQuery functions with pure javascript. However, the ajax calls are giving me problems. Here is my successful jQuery and my unsuccessful JavaScript:

<strong>Original JQuery</strong>

  url: locals.ajax_url,
  method: 'post',
  context: this,
  data: {
    action: 'get_more_posts',
    page: page,
    loop: typeof loop !== 'undefined' ? loop : locals.wp_query

<strong>New JavaScript</strong>

var req = new XMLHttpRequest();'POST', locals.ajax_url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
var l = typeof loop !== 'undefined' ? loop: locals.wp_query;
var s = 'action=get_more_posts&amp;page=' + page + '&amp;loop=' + encodeURIComponent(JSON.stringify(l));

The jQuery works, but the javascript isn't handling the the loop variable correctly (variable "l").

The jQuery sends an HTTP request with something like this:


But the javascript version sends something like this:


So the jQuery is sending square brackets while the javascript is sending squiggly brackets (amongst other things).

I know there are several approaches to fixing this, but I can't quite get any of them to work. I would love to change the request header to "application/json", but then I can't get wordpress to recognize the other variables (action, page). Otherwise, I just need the loop variable to encode/decode correctly.

Here's the variable if that helps:

&lt;script&gt;var loop = &lt;?= json_encode($loop); ?&gt;;&lt;/script&gt;

Here's the php function if that helps (works with the jQuery version):

function get_more_posts() {
  $args = $_REQUEST['loop']['query'];
  $args['paged'] = $_REQUEST['page'];
  $loop = new WP_Query($args);

Not sure if I need to make changes in php or javascript, but the answers can't involve any external libraries, and keep in mind I'm working with WordPress. Let me know if you need any more information. Thanks in advance.