In the widget function of my WP_Widget class in my wordpress plugin, I have a php array variable named $hello. I want to pass this variable to javascript. I have seen the function wp_localize_script and tried to use it. But it is not working from inside the function. How to make it work?
This is the code in widget() function of my WP_Widget class.
wp_register_script('color-script', plugin_dir_url(__FILE__).'scripts/custom.js');
wp_enqueue_script('color-script');
$data = array("text_color" => $instance['text-color'], "bg_color" => $instance['bg-color'], "button_color" => $instance['button-color']);
wp_localize_script('color-script', 'php_data', $data);
This is the javascript in custom.js.
document.getElementById("wid-small-div").style.color = php_data.text_color;
document.getElementById("wid-small-div").style.background = php_data.bg_color;
It’s not that simple. PHP is a server-side language which means the server receives a request, renders a page and then sends it to the browser. Javascript is a client-side language (at least in your case) which means it is applied by the browser on the client side after it receives the rendered page from the server.
You can’t just pass PHP variables to Javascript because they are not accessible by the browser and the PHP has already finished executing before the JS even comes into play.
In order to do this you need an AJAX request or something similar, which is an asynchronous call to the server (i.e. to a PHP function) made by Javascript that allows you to pass data (usually JSON) between the server and client without reloading the page. jQuery has very robust built in AJAX support that makes this fairly easy.
In your case you just need to use jQuery to send a request to a PHP function on the server that returns the
$hello
array so you can use it in JS. You can usewp_localize_script()
to achieve this too for simple situations like passing variables between PHP and JS but we can’t troubleshoot your code without seeing your code.All you need to do is print the contents of the
$hello
variable as a JS-variable:Then once the widget is rendered you will have a
hello
variable in JS.Yes, you can pass PHP variables to javascript, but you can’t pass variables from Javascript to PHP. PHP is processed server-side, so by the time the page is showed on the browser, all PHP has been already processed and Javascript will start its work.
You can try it this way: