I’m using Webpack and Wordpress.
When I enqueue example ajax script in functions like so:
wp_enqueue_script( 'script-name', get_stylesheet_directory_uri() . '/js/example_script.js', array(), false, true );
wp_enqueue_script( 'general-bundle', get_template_directory_uri() . '/dist/bundle.app.js', array(), false, true );
wp_localize_script('script-name', 'fih_ajax', array( 'url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce(‘example-nonce')));
It works.
The problem is when I remove example_script.js from functions.php, and import it into app.js (because I want to include it into bundle.app.js) :
import "./example_script.js";
Console shows:
ReferenceError: Can't find variable: fih_ajax
example_script.js part:
$.ajax({
url: fih_ajax.url,
type: 'POST',
data: {
action: 'fimgh_ajax',
nonce: fih_ajax.nonce,
href: hrefValue //the-data
},
in bundle.app.js:
https://jsfiddle.net/4052vaun/1/
CodePudding user response:
wp_localize_script handle needs to point into one that is in use, in this case 'general-bundle’.
Changing
wp_localize_script('script-name', 'fih_ajax', array( 'url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce(‘example-nonce')));
into
wp_localize_script('general-bundle', 'fih_ajax', array( 'url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce(‘example-nonce')));
solved the problem. Thanks to @HowardE comment