How to add ajax url to js using wp_add_inline_script()?

I usually enable ajax in a js script by using wp_localize_script like this

wp_localize_script( 'map-scripts', 'ajax_info', array( 'ajax_url' = admin_url( 'admin-ajax.php' ) ) );

but now I see it is best practice to use wp_add_inline_script, which I find harder to use.

I am not able to pass an array with this method. I tried the following but it does not look the same:

$ajax_arr = array( 'ajax_url' = admin_url( 'admin-ajax.php' ) );
$ajax_json = json_encode($ajax_arr);
$ajax_info  = 'ajax_info = '.json_encode($ajax_json).';';
wp_add_inline_script( 'map-scripts', $ajax_info, 'before' );

Do you know the proper way to do it?

Topic wp-localize-script ajax Wordpress

Category Web


If anyone still needs it:

wp_add_inline_script(
  'map-scripts',
  'const ajax_info = ' . json_encode(array(
      'ajaxurl' => admin_url('admin-ajax.php'),
   )),
  'before'
);

but, it's good practice to use nonce as well for better security:

wp_add_inline_script(
  'map-scripts',
  'const ajax_info = ' . json_encode(array(
      'ajaxurl' => admin_url('admin-ajax.php'),
      'nonce' => wp_create_nonce('your_nonce_handler'), //the more specific the better
      'your_other_item' => "some additional data", //etc.. 
   )),
  'before'
);

https://developer.wordpress.org/reference/functions/wp_add_inline_script/

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.