Last active
December 14, 2015 21:51
-
-
Save glueckpress/4722102 to your computer and use it in GitHub Desktop.
[WordPress] Basic routine to pass an array of values from PHP to JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* Create an array of data to pass */ | |
$obj = array( | |
'foo' => $foo, | |
'bar' => $bar, | |
'multifoo' => array( 'foo1', 'foo2' ) | |
); | |
/* Enqueue javascript (assuming jQuery has been enqueued already) */ | |
wp_enqueue_script( 'script-handler', 'plugin-script.js', 'jquery', false, true ); | |
/* Pass array as javascript object */ | |
wp_localize_script( 'script-handler', 'obj', $obj ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(function($){ | |
// Create object from PHP array values | |
$.Obj = { | |
foo : obj.foo, | |
bar : obj.bar, | |
multifoo : obj.multifoo // obj.multifoo[0], obj.multifoo[1] usw. | |
} | |
// Check values in console | |
console.log( | |
'foo: ' + $.Obj.foo +"\n"+ | |
'bar: ' + $.Obj.bar +"\n"+ | |
'multifoo [0]: ' + $.Obj.multifoo[0] +', '+ | |
'multifoo [1]: ' + $.Obj.multifoo[1] +', '+ | |
'multifoo [2]: ' + $.Obj.multifoo[2] | |
); | |
}(jQuery)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment