Ajax requests without JQuery

Coming back to this on a new application. I just solved this using Angular, and a similar approach could be used with vanilla JS.

First, give Javascript access to the admin-ajax.php URL, something like:

echo "<script type="text/javascript">var ajaxurl="".admin_url("admin-ajax.php')."'</script>";

Next, in functions.php, register the action you want the Ajax to perform:

add_action("wp_ajax_infiniteScroll", "infiniteScroll");
add_action("wp_ajax_nopriv_infiniteScroll", "infiniteScroll");

…and add an action handler which corresponds to the second parameter of the above actions:

function infiniteScroll() { 
    // This is what's returned to the client.
    echo "foo"; 
    die(); 
}

Now, all your ducks are in a row. Call ajaxurl with the action parameter set to the action you made above, and everything should work (below example with Angular):

$http({ url: ajaxurl + "?action=infiniteScroll" })
    .success(thenPopulate)
    .error(thenError);

Most solutions “require” JQuery (don’t need it) and wp_enqueue_scripts() and a few other “convenience” functions (also not necessary). The main thing is, make the URL available to your JS, register an action, and send that action in your request.

For those concerned about the globally visible ajaxurl, all of the other solutions I’ve read about use wp_localize_script() which makes a global variable anyway. With the above method, you can at least have a little control over its scope.

Leave a Comment