Wp_localize_script not working in Sage 9?

First of all: I know there are several topics in this forum already touching issues like that, but I have read them all and they do not provide a solution.

My problem is the following:
I’m trying to localize my scripts to pass a nonce to the main javascript file. However it does not seam to work in Sage 9. Here is my code:

wp_enqueue_script('sage/main.js', asset_path('scripts/main.js'), ['jquery'], null, true);

$ajax_params = array(
    'ajax_url' => admin_url('admin-ajax.php'),
    'ajax_nonce' => wp_create_nonce('my_nonce'),
);

wp_localize_script('sage/main.js', 'ajax_object', $ajax_params);

The JS variable “ajax_object” remains in the script. Do you face similar troubles (is it a bug) or am I doing something the wrong way?

5 Likes

Have you found a solution to this yet? I am trying to do the same thing.

Not yet. I’ll keep this thread updated, as soon as I’ll make progress.

You’ve only posted a small snippet of your code, but based on some experimentation with a clean Sage install, my guess is that you’re not putting these function calls inside of an appropriate action. In app/setup.php, the original call to wp_enqueue_script() is wrapped in an add_action() call to wp_enqueue_scripts. When the code you posted is put inside that call, it appears to work correctly:

// app/setup.php
add_action('wp_enqueue_scripts', function () {
    wp_enqueue_script('sage/main.js', asset_path('scripts/main.js'), ['jquery'], null, true);
    $ajax_params = array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'ajax_nonce' => wp_create_nonce('my_nonce'),
    );

    wp_localize_script('sage/main.js', 'ajax_object', $ajax_params);
}, 100);
// resources/assets/scripts/routes/common.js
export default {
  init() {
    // eslint-disable-next-line no-undef
    console.log(ajax_object);
  },
  finalize() {},
};

(Without the line // eslint-disable-next-line no-undef, yarn build will throw an error when you try to compile your JS.)

// browser console
Object { ajax_url: "http://sand.box/wp-admin/admin-ajax.php", ajax_nonce: "1a1b086c5c" }

Just running wp_enqueue_script/style on its own has no effect: It needs to be hooked to an action so it’s run at the appropriate time. wp_enqueue_scripts is generally a good hook to grab onto for that purpose.

13 Likes

In support to this I suggest to read this article. :raised_hands:

The same setup works for me without any issues.

I was having the same problem (non problem?)

Issue was that eslint doesn’t detect the variable. Simply disabling it for that line as indicated above worked for me.

// eslint-disable-next-line no-undef

Thanks alwaysblank!

Alternatively, add it to globals in the ESLint config:

4 Likes

Hi, I am having the same issue. I followed the same processed as describied above but I am still getting “error ‘admin_url’ is not defined no-undef” when trying to compile.
I added the following line in routes/common.js without success "
// eslint-disable-next-line no-undef
console.log(ajax_object);"
Any thought?

Here is my code:
// app/setup
add_action(‘wp_enqueue_scripts’, function () {
wp_enqueue_script(‘sage/main.js’, asset_path(‘scripts/main.js’), [‘jquery’], null, true);

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

}, 100);

function advanceSearch(){
/* function code goes here */

header(“content-type: application/json”);
echo json_encode($list);
die;
}
// main.js
$(’#post-subject’).on(‘click’, function(){
var postData = {
action: ‘advanceSearch’,
search_post: postblog,
};
jQuery.ajax({
url: admin_url.ajax_url,
type: ‘post’,
data: postData,
}).done(function(response){
console.log(response);
})
})

After running yarn I get this error message from main.js:
“error ‘admin_url’ is not defined no-undef”

See above:

1 Like

Thanks @ben for responding. “wp” is already set to true under global object in eslintrc.js.

According to the eslint online documentation https://eslint.org/docs/rules/no-undef
it seems like the js object “admin_url” declared in the wp_localize_script: wp_localize_script( ‘sage/main.js’, ‘admin_url’, array(
‘ajax_url’ => admin_url( ‘admin-ajax.php’ )
) );
has to be explicitly mentioned in a /global …/ comment. I tried to do the following in common.js: but I am not sure if it is the right way of getting around that “no-undef” lint error

init() {
/global admin_url/
/eslint no-undef: “error”/
},

You would need to add admin_url to the globals definition:

"globals": {
  "wp": true,
  "admin_url": true
},

The globals definition in your ESLint config is essentially telling ESLint “Please don’t check to see if the variables I’ve set to ‘true’ here are defined in my scripts: they will be globally available when the scripts run.”

3 Likes

That fixed the ESlint error. Thanks, @alwaysblank !

You can also get around this by adding the following:

const admin_url = window.admin_url;