2

I'm trying to pass PHP data to a JS script. I'm using the wp_localize_script function.

wp_register_script('googlechart', 'https://www.gstatic.com/charts/loader.js');
wp_register_script('mygaloochart_script', plugins_url('chart.js', __FILE__), array('googlechart'));

//I'm not using $atts directly for reasons
$dataToBePassed = array (
        'chart' => $atts['chart'],
        'element' => $atts['element'],
        'elementtype' => $atts['elementtype'],
        'title' => $atts['title']
);

wp_localize_script('mygaloochart_script', 'php_vars', $datatoBePassed);

wp_enqueue_script('googlechart');
wp_enqueue_script('mygaloochart_script');

This is the first line of the JS script mygaloochart_script:

console.log(php_vars.chart);

However, I get the following error in the console:

TypeError: php_vars is null

What am I doing wrong?

2 Answers 2

2

The name of your array is $dataToBePassed. However you are passing $datatoBePassed in your wp_localize_script function. Big T, small t. PHP variable names are case sensitive.

Sign up to request clarification or add additional context in comments.

1 Comment

To the people coming to this from tutsplus here is where the mistake began: code.tutsplus.com/tutorials/…
0

I am unable to comment due to my reputation. Just curious to ask, did you hook the function something like the below?

Update

function add_vars_to_js(){

wp_register_script('googlechart', 'https://www.gstatic.com/charts/loader.js');
wp_register_script('mygaloochart_script', plugins_url('chart.js', __FILE__), array('googlechart'));

//I'm not using $atts directly for reasons
$dataToBePassed = array (
        'chart' => $atts['chart'],
        'element' => $atts['element'],
        'elementtype' => $atts['elementtype'],
        'title' => $atts['title']
);

wp_localize_script('mygaloochart_script', 'php_vars', $datatoBePassed);

wp_enqueue_script('googlechart');
wp_enqueue_script('mygaloochart_script');
}

add_action('wp_enqueue_scripts', 'add_vars_to_js');

7 Comments

I didn't. Is this necessary? It's not mentionned in the wp_localize_script doc.
What should be the syntax? The function called in my script is called drawChart() (sorry, new to Wordpress!).
Updated the answer. If the js is for admin area, add the hook like this add_action('admin_enqueue_scripts', 'add_vars_to_js');
I'm getting Fatal error: Cannot redeclare add_vars_to_js() (previously declared in C:\wamp64\www\wordpress\wp-content\plugins\mygaloochart\chart.php:40) in C:\wamp64\www\wordpress\wp-content\plugins\mygaloochart\chart.php on line 40
This is an example of a function name. Try another name like olivier_function_js or whatever
|

Your Answer

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