wordpress passing variable to javascript

I’m trying to pass a variable to a javascript file from a plugin. Here is my plugin code:

<?php
/**
 * @package JS Test
 * @version 1.0
 */
/*
Plugin Name: JS Test
Description: JS Test.
*/


add_action('init', 'my_init');
add_action( 'wp', 'test_js' );

function my_init() {
  wp_enqueue_script( 'jquery' );
}

function test_js() {

   wp_register_script ('testjs', plugins_url('jstest.js', __FILE__));
   wp_enqueue_script ('testjs');
   $my_arr = array('my array',
     'name' => 'Test',
   );
   $my_json_str = json_encode($my_arr); 

   $params = array(
     'my_arr' => $my_json_str,
   );

   wp_enqueue_script('my-java-script');
   wp_localize_script('my-java-script', 'php_params', $params);
}

Here is the jstest.js file:

Read More
    jQuery(document).ready(function() {
      alert ('test');
      var my_json_str = php_params.my_arr.replace(/&quot;/g, '"');
      var my_php_arr = jQuery.parseJSON(my_json_str);
      alert(php_params);    
    });

What I get is this error in JavaScript:
ReferenceError: php_params is not defined
Anybody see what I’m doing wrong?

Related posts

Leave a Reply

1 comment

  1. You Don’t need to enqueue a script just for your localized parameters you can use your testjs for that, here is a quick plugin i cooked up to test:

    <?php
    /*
    Plugin Name: PHP to JS
    Plugin URI: http://en.bainternet.info
    Description: wordpress passing variable to javascript 
    http://stackoverflow.com/questions/12761904/wordpress-passing-variable-to-javascript
    Version: 1.0
    Author: Bainternet
    Author URI: http://en.bainternet.info
    */
    
    add_action('init', 'my_init');
    add_action( 'wp', 'test_js' );
    
    function my_init() {
     /wp_enqueue_script( 'jquery' );
    }
    
    function test_js() {
    
       wp_register_script ('testjs', plugins_url('jstest.js', __FILE__));
       wp_enqueue_script ('testjs');
       $my_arr = array('my array',
         'name' => 'Test',
       );
       $my_json_str = json_encode($my_arr); 
    
       $params = array(
         'my_arr' => $my_json_str,
       );
    
    
       wp_localize_script('testjs', 'php_params', $params);
    }
    
    add_action('wp_footer','footertestjs');
    
    function footertestjs(){
        ?>
        <script>
          jQuery(document).ready(function() {
            alert ('test');
            var my_json_str = php_params.my_arr.replace(/&quot;/g, '"');
            var my_php_arr = jQuery.parseJSON(my_json_str);
            alert(php_params);    
          });
        </script>
        <?php
    }
    

    as you can see here the wp_localized_script uses the same script as you enqueue and not a fake script.