"how to load ajax in wordpress" Answer’s


As per your request I have put this in an answer for you.

As Hieu Nguyen suggested in his answer, you can use the ajaxurl javascript variable to reference the admin-ajax.php file. However this variable is not declared on the frontend. It is simple to declare this on the front end, by putting the following in the header.php of your theme.

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

As is described in the Wordpress AJAX documentation, you have two different hooks - wp_ajax_(action), and wp_ajax_nopriv_(action). The difference between these is:

  • wp_ajax_(action): This is fired if the ajax call is made from inside the admin panel.
  • wp_ajax_nopriv_(action): This is fired if the ajax call is made from the front end of the website.

Everything else is described in the documentation linked above. Happy coding!

P.S. Here is an example that should work. (I have not tested)

Front end:

<script type="text/javascript">
        url: ajaxurl,
        data: {
            action: 'my_action_name'
        type: 'GET'

Back end:

    function my_ajax_callback_function() {
        // Implement ajax function here
    add_action( 'wp_ajax_my_action_name', 'my_ajax_callback_function' );    // If called from admin panel
    add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_callback_function' );    // If called from front end

UPDATE Even though this is an old answer, it seems to keep getting thumbs up from people - which is great! I think this may be of use to some people.

WordPress has a function wp_localize_script. This function takes an array of data as the third parameter, intended to be translations, like the following:

var translation = {
    success: "Success!",
    failure: "Failure!",
    error: "Error!",

So this simply loads an object into the HTML head tag. This can be utilized in the following way:


wp_localize_script( 'FrontEndAjax', 'ajax', array(
    'url' => admin_url( 'admin-ajax.php' )
) );

The advantage of this method is that it may be used in both themes AND plugins, as you are not hard-coding the ajax URL variable into the theme.

On the front end, the URL is now accessible via ajax.url, rather than simply ajaxurl in the previous examples.

Wednesday, March 31, 2021
answered 10 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :