Add ajax_url to main.js

Hi Guys,

I’m trying to add the variable ajax_url to main.js.

For that I’m doing the following:

add_action(‘wp_enqueue_scripts’, function () {

wp_enqueue_style('sage/main.css', asset_path('styles/main.css'), false, null);
wp_enqueue_script('sage/main.js', asset_path('scripts/main.js'), ['jquery'], null, true);
wp_localize_script('sage/main.js', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

}, 100);

For some reason it seems not work inside my route JS files?

I still got undefined on ajax_url =/

Hey!

Try accessing it with window.my_ajax_object.ajax_url

And use it like

const ajax_url = window.my_ajax_object.ajax_url || false; // Default as false if not set

if (ajax_url) {
  ...
}

I usually add it like

wp_localize_script('sage/main.js', 'sage', array(
  'ajax_url' => admin_url('admin-ajax.php'),
));

And use it as window.sage.ajax_url but you should be able to call the object whatever you want.

Tip: Look at the page source code and search for your javascript variable my_ajax_object and you should see where and how it is output to the page

Where are you placing this @stefanlindberg?

const ajax_url = window.my_ajax_object.ajax_url || false; // Default as false if not set

I’ve placed it in main.js and also tried in common.js but the variable is always undefined…

wp_localize_script is definitely setup correctly as I can access the var in browser console.

…to clarify further, I’m trying to access the const in other routes (e.g. sinlge.js) perhaps im misunderstanding the scope of the variable?

I place the code in the route like scripts/routes/single.js

// single.js

export default {
  init() {
    const ajax_url = window.my_ajax_object.ajax_url || false;
    
    if (ajax_url) {
      console.log(ajax_url); // eslint-disable-line
      $.ajax({
        url: ajax_url,
        ...
      });
    }
  },
};

I access it through the window object so the scope is global and I don’t think this is the issue. Double check so you havn’t misspelled something.

Also in the second parameter of localize_script did you go for ‘sage’ or ‘my_ajax_object’ ?

Do you access the variable with just my_ajax_object.ajax_url in the console?

ah ok yep thats what i’m doing now - I’d mistaken the const as being global throughout main.js…