41

I am trying to create a ajaxform on the front side. I am using the code

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

for which I am getting error

Uncaught ReferenceError: ajaxurl is not definedworklorAjaxBookForm @ 
?page_id=2:291onclick @ ?page_id=2:202

While using similar code on the admin backend works. What url must I use to process the ajax request?

1

5 Answers 5

75

In backend there is global ajaxurl variable defined by WordPress itself.

This variable is not created by WP in frontend. It means that if you want to use AJAX calls in frontend, then you have to define such variable by yourself.

Good way to do this is to use wp_localize_script.

Let's assume your AJAX calls are in my-ajax-script.js file, then add wp_localize_script for this JS file like so:

function my_enqueue() {

    wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );

    wp_localize_script( 'ajax-script', 'my_ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );

After localizing your JS file, you can use my_ajax_object object in your JS file:

jQuery.ajax(
    {
        type: "post",
        dataType: "json",
        url: my_ajax_object.ajax_url,
        data: formData,
        success: function(msg){
            console.log(msg);
        }
    });
8
  • 2
    can I use wp_localize_script without having to use wp_enqueue_scritp? Commented Jun 3, 2015 at 8:12
  • 1
    You use script handle in wp_localize_script, so you have to use wp_enqueue_script for at least one of your scripts. But... Not using wp_enqueue_script is not a good idea (you risk some conflicts and dependencies problems). Commented Jun 5, 2015 at 6:04
  • i don't have any external script to load, i just want to use ajaxurl to make an ajax call. is that not possible?
    – R T
    Commented Sep 23, 2015 at 7:05
  • And where will you put this AJAX call? As inline script? It's a very bad idea... Commented Sep 23, 2015 at 7:07
  • i've a separate form, in that i'm managing validation and on submit, an ajax call to submit form with of course wordpress way by adding hook. anyway I've figured out the way for using ajaxurl.
    – R T
    Commented Sep 23, 2015 at 7:25
57

to use ajaxurl directly, in your plugin file add this:

add_action('wp_head', 'myplugin_ajaxurl');

function myplugin_ajaxurl() {

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

you can then use the ajaxurl for ajax request.

5
  • 2
    This answer makes ajaxurl similarly the same as the default usage. Which is much better than the accepted answer. Commented Dec 25, 2018 at 4:01
  • true, but it's useless if you are using it in a .js file.
    – Jules
    Commented Mar 20, 2019 at 7:56
  • 1
    @Jules ajaxurl is still available in a *.js file. To do so, you may need to declare the ajaxurl variable early on of the page load. Another thing to consider is the calling of the external *.js file of yours. The external file should be called AFTER the ajaxurl has been instantiated and be given the right URL value. Commented Nov 9, 2019 at 0:53
  • what's an error in console? Commented Jan 29, 2020 at 7:10
  • 1
    What about conflicts with other plugins or themes that declare the variable in the same way? I do believe you should at least namespace the variable. Anyway, I think the accepted answer has less potential to cause trouble/conflicts later on. But I guess if you are well aware what you are doing, this approach is fine.
    – Jules
    Commented Sep 22, 2020 at 14:42
3

The 2021 way is a bit different ;-)

function my_enqueue() {

    wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );

    wp_add_inline_script( 'ajax-script', 
        'const myVariables = ' . json_encode( 
                                    array(
                                        'ajaxUrl' => admin_url( 'admin-ajax.php' ),
                                        ) ),
        'before' );

}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );

Source: https://developer.wordpress.org/reference/functions/wp_add_inline_script/#comment-4632

1
  • 1
    I just stumbled across this same solution today, there's more information regarding when to use wp_add_inline_script() vs wp_localize_script() on the wp_localize_script documentation too, if you're curious. Commented Oct 25, 2021 at 19:24
0

i have use below code in wordpress site.
we can use below code for setup ajaxurl like this.

<?php echo esc_url(admin_url('admin-ajax.php')); ?>  

i have also added ajax example were we can use above line.

 function setNotificationRead() {
        fetch('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
            },
            body: `action=yourFunctionsAction`,
            credentials: 'same-origin'
        }).then(response => {
            return response.json();
        }).then(data => {
            if (data.status === 'true') {
                console.log('Do something...');
            }
        });
    }
0

I got this to work after many hours...and trials and errors. So, I do share how to make ajax work in wordpress with an example (started with https://www.tweaking4all.com/web-development/wordpress/wordpress-ajax-example/#comment-562814 and adapted the example)

--use chrome developer tools and take off cache from network tab --look to console if you get any errors, first goal is to get to console "ready!" when you click the button and if all works you get some nice output too!

--add to wordpress website as custom html block:

<div id="receiving_div_id">
   <p>Nothing loaded yet</p>
</div>
<button id="button_to_load_data">Get Ajax Content</button>

--add to theme/js/button.js (create js folder):

   jQuery("#button_to_load_data").click(function() {
        console.log( "ready!" );
      var data = {
         'action'   : 't4a_ajax_call', // the name of your PHP function!
         'function' : 'show_files',    // a random value we'd like to pass
         'fileid'   : '7'              // another random value we'd like to pass
         };
       
      jQuery.post(my_ajax_object.ajax_url, data, function(response) {
         jQuery("#receiving_div_id").html(response);
      });
   });

--add to theme functions.php:

 /* custom script in theme functions.php */

/* read button.js (->my-script) and localize admin-ajax.php for my-script */
function add_my_script() {

  wp_enqueue_script( 'my-script', 
         get_template_directory_uri() . '/js/button.js', 
         array ( 'jquery' ), 
         false,
         true
  );
  
      wp_localize_script( 'my-script', 'my_ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

}
add_action( 'wp_enqueue_scripts', 'add_my_script' );



/*ajax result */

add_action('wp_ajax_t4a_ajax_call', 't4a_ajax_call');  // for logged in users only
add_action('wp_ajax_nopriv_t4a_ajax_call', 't4a_ajax_call'); // for ALL users

function t4a_ajax_call(){

   echo 'Ajax call output:';

   echo '<pre>';
   var_dump($_POST);
   echo '</pre>';

   wp_die();// this is required to terminate immediately and return a proper response
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.