Wp_localize_script not working in Sage 9?

sage9

#1

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?


Refer to main.js using wp_enqueue_script in a custom plugin file
#2

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


#3

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


#4

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.


#5

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


#6

The same setup works for me without any issues.


#7

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!


#8

Alternatively, add it to globals in the ESLint config:


#9

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?


#10

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”


#11

See above:


#12

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


#13

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”/
},


#14

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.”


#15

That fixed the ESlint error. Thanks, @alwaysblank !