WordPress Ajax Error: ajaxurl is not defined

Plugin and theme authors have been making faster and more powerful themes for WordPress thanks to the power of asynchronous Javascript calls (Ajax).

Thanks to ajax you can for example load the content of a post without actually changing the page or submit a form and get the server response instantly without any reload. Let’s look at a simple example with jQuery:

jQuery.ajax({
    type: "post",
    dataType: "json",
    url: ajaxurl,
    data: formData,
    success: function(msg){
        console.log(msg);
    }
});

This would send the data of the form to the url ‘ajaxurl’. And although this would work for a plugin in the admin, it doesn’t work in a theme, you would get an error:

Uncaught ReferenceError: ajaxurl is not defined

To have the ajaxurl variable available on the frontend the easiest way is to add this snippet to you theme’s function.php file:

add_action('wp_head', 'myplugin_ajaxurl');

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

This get the url of the ajax submission page and creates a variable in the head of the html with it. Now ‘ajaxurl’ is available in your theme so you can start making it more modern and dynamic.

Leave a Reply

Your email address will not be published. Required fields are marked *