Search code examples
javascriptajaxwordpresslive

WordPress AJAX live search without jQuery


I'm trying to make ajax live search on WP website without usage of jQuery cause I don't want to load additional 80kb for this feature. I already made it work with jQuery, but when I try to rewrite script to work with Vanilla jS, I always got the issue

wp-admin/admin-ajax.php 400 (Bad Request)

working code

jQuery.ajax({
    url: '<?php echo admin_url('admin-ajax.php'); ?>',
    type: 'post',
    data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
    success: function(data) {
        jQuery('#datafetch').html( data );
    }
});

VANILLA JS CODE that doesn't work

var request = new XMLHttpRequest();
request.open('POST', '<?php echo admin_url("admin-ajax.php"); ?>', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

request.onload = function () {
  if (this.status >= 200 && this.status < 400) {
    console.log('if');
  } else {
    console.log('else');
  }
};

request.onerror = function() {
  console.log('onerror');
};

var data = document.getElementById('keyword').value;
request.send(data);

Solution

  • The obvious problem I see without knowing your problem is that request.send(data); does not equal to { action: 'data_fetch', keyword: jQuery('#keyword').val() } instead you should be writing something like this request.send('action=data_fetch&keyword='+data);

    Also, depending on the data value you are passing you may need to encode it. Again, it is somewhat hard to help you without knowing exactly the problem you are having.