I've searched a lot for this and I seem to get different answers.
In my situation, my jQuery function has to use a PHP variable from a different file.
How can I accomplish this? Clear and simple answer would be greatly appreciated.
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.
Sign up to join this communityI've searched a lot for this and I seem to get different answers.
In my situation, my jQuery function has to use a PHP variable from a different file.
How can I accomplish this? Clear and simple answer would be greatly appreciated.
In general, this function lets you localize your JS strings, but you can also use it to set global JS variables:
function set_my_js_var() {
// logic here for returning the right JS var
$myVar = "Hello World";
return $myVar;
}
function load_fe_scripts() {
wp_enqueue_script( 'global-js-var', get_template_directory_uri() . '/js/my_file.js' );
$localize_array = array(
'my_js_var' => set_my_js_var()
);
wp_localize_script( 'global-js-var', 'my_global', $localize_array );
}
add_action('wp_enqueue_scripts', 'load_fe_scripts');
You can now acces the var in your JS File by my_global.my_js_var
You could use ajax to get the value from a function read about it here: http://codex.wordpress.org/AJAX_in_Plugins
you can also save the variable in the database with transients if the function runs on every load. http://codex.wordpress.org/Transients_API
then use http://codex.wordpress.org/Function_Reference/wp_localize_script to load the var to a global javascript var.
Update: This is a ugly way to do this. In your template where you want to save the var:
<script type="text/javascript">
<?php print_var(); ?>
</script>
And in your function:
<?php
// register a global outside the function
global $myVar;
function MyFunc(){
global $myVar;
...
//save the var in the global!
$MyVar = $a;
...
}
//function
function print_var(){
global $MyVar;
echo "var myGlobalJsVar = ". $MyVar .";";
}
?>
<script type="text/javascript">
var a = <?php echo $a=1; ?>
// OR
var a = <?php global $a; echo $a; ?>
</script>
We can directly use PHP variable in javascript as i showed in example
If your php code and javascript code in same page then you can use first approach. Else your php code in different page and included it in current page then use second approach.
In second approach i used global keyword.
Please go through this link PHP Language Variables Scope