1

I'm trying to work out how to send a PHP variable from a page template to an AJAX function (which in turn pulls data via a function in functions.php using admin-ajax.php). I understand I'm meant to use wp_localize_script, but can't get it to work in either my page template or functions.php.

In functions.php:

add_action( 'wp_enqueue_scripts', 'enqueue_theme_scripts' );
function enqueue_theme_scripts() {  
    wp_register_script('xxx', get_stylesheet_directory_uri() . '/assets/js/xxx.js', array ( 'jquery' ), null, true);
    wp_enqueue_script('xxx');
    wp_localize_script( 'xxx', 'yyy', array( 'ajax_url' => admin_url( 'admin-ajax.php'), 'a_value'=> '10' ) );
    wp_localize_script( 'xxx', 'zzz', 'hello' );
}

So I'm trying to retrieve 'hello' as a variable in xxx.js. My understanding is that with the code above I should be able to do:

alert(zzz);

But it doesn't work. What am I doing wrong?

And how does it work if I want to grab a PHP variable from my page template php file, not from functions.php? I can't find any online examples...

6
  • are you expecting it in frontend or backend? did you try to view source code to see if /assets/js/xxx.js is loaded or not? Commented Apr 13, 2020 at 7:48
  • Front-end, and yep, xxx is loading fine.And if I do alert("hi"), it comes up. So it's literally just wp_localize_script that isn't working for me. (Although my wp_localize_script going to admin-ajax.php has always worked).
    – JohnG
    Commented Apr 13, 2020 at 10:26
  • I think it is there. Only that alert not work, did you try to type zzz in inspector console to see if variable exists? If it exist, you alert(zzz) in console should work. I have tried your code, it works and it looks alright. If js file is loaded, when you view source and search zzz should be somewhere around. For the second question, what do you want to accomplish specifically. Would you mind giving examples? Commented Apr 13, 2020 at 10:33
  • It all magically works this morning. I'm mystified, as I spent hours last night trying to crack it. No problems whatsoever now :/
    – JohnG
    Commented Apr 13, 2020 at 10:41
  • Thanks for taking an interest though! :)
    – JohnG
    Commented Apr 13, 2020 at 10:41

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.