WordPress AJAX call with Javascript (Not JQuery)

This will be a reasonably quick post, I just wanted to talk about how to make a call to admin-ajax.php without using stupid JQuery.

So let’s get right into it. First I have to reference the tutorial that I followed to start using AJAX calls to begin with, this guy right here. It’s a pretty descriptive tutorial, but a little copy and paste. And it focuses on using JQuery, as do most AJAX calls. Especially in relation to wordpress and the admin-ajax.php structure.

The first, and main, issue with using JavaScript to run these calls is the default header that JQuery uses.

You need to make sure that you utilize the Content-Type header x-qqq-form-urlencoded because of how the built in service that WordPress uses to respond works. It doesn’t accept json data like most modern API’s.

  • Content-Type: “application/x-www-form-urlencoded; charset=UTF-8”

So this also points out why we can’t send json data, it’s expecting a urlencoded string. If you’re not familliar, you may recognize them from URL’s you’ve used; url?data=data&moredata=moredata etc. We do want to send this in the body, I believe because this is a POST request, so without the ? to start off we can just fill out our string in back-ticks and use string literals to fill in our variables.

And voila! This is how I managed to send my request using JavaScript. I used the XMLHttpRequest function to do this, at first, because it has more documentation, but I do want to try converting it to fetch to make this a little more modern still.

EDITS: if you’ve checked, or checked back for that matter, you may have noticed some edits. I’ve been ironing out the kinks I discovered working more with ajax and have been keeping the repo updated. The information above should still be reflective of how I’ve moved to jquery, and there are a few branches that I made to show my progression through different methods.

Here is the repository for the above tutorials plugin with JavaScript implementation 🙂

-funcyChaos