WordPress how to use wp_localize_script()

I have trouble localizing PHP variables for use in JS in WP.

I have a plugin I’m working on, which has several scripts that I enqueue with wp_enqueue_scripts() (suppose the handle I gave it is ‘my_script’), which works as intended.

However, on one page I would like to submit a value (a counter in a foreach loop, which might change) from PHP to JS and I am unclear how to properly do this.

Assume I have this in my_page.php which is a submenu page in my plugin:


$my_counter = get_my_count();

    wp_localize_script(
        'my_script',
        'my_js_object',
        array(
            'ajax_url' => $ajax_url,
            'my_counter' => $my_counter
        )
    );

and my JS in my_script.js:

console.log(my_js_object.my_counter);

From what I understand, my_script points to the JS-file I enqueued in functions.php. However, this isn’t working, and my console tells me ‘my_js_object’ is not defined.

What do I localize where to get this to work?