Vanilla JS Ajax - Request and method problems

I have stopped using jQuery. It feels nice to save 85 kB on each pageload. However I have an ajax problem.

Old jQuery Ajax

This was about what my old jQuery ajax looked like.

    method: "POST",
    url: 'ajax',
    data: {
        data: test
    success : function(response) {

My new ajax call

var request = new XMLHttpRequest();"POST", "ajax", true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onreadystatechange = function () {
    if (request.readyState != 4 || request.status != 200) return; 
    console.log( request.responseText );

1. Request ajax don’t work

This works with jQuery but not with vanilla (plain) javascript.

if( kirby()->request()->ajax() )

Why does the above don’t work with kirby()->request()->ajax(). The ajax call is working fine without it.

2. Method POST don’t work

Method POST don’t work with vanilla JS. However I can use 'method' => 'ALL' but I would prefer just POST like before.

Because the vanilla XMLHttpRequest does not add the necessary X-Requested-With header by default. The following line should make it work:


What do you mean by “does not work”?

Great! That solved it all, both questions.


PS: Your forum threads are always very detailed and easy to understand and solve. I think that the last step to the solution is not very far: Taking a look into the Kirby source code. Because that’s often what I do.