Why does Javascript file get empty array from php file? Wordpress plugin

I am creating the plugin that calculates income taxes. I don't need to reload page so I am going to use ajax. I need to get a plugin's path and transfer it to javascript file.

$my_data_array = [];

add_shortcode('penalty', 'penalty_calculator');
add_action( 'wp_enqueue_scripts', 'my_styles_scripts' );

function my_styles_scripts(){
    global $my_data_array;

    wp_register_script( 'my-js', plugins_url( 'js/my_functions.js', __FILE__ ), array('jquery'), '', true );

    wp_enqueue_script( 'my-js' );

    wp_localize_script( 'my-js', 'dataObj', $my_data_array );

function penalty_calculator(){
    global $my_data_array;

    $my_data_array= [
        'path' => plugin_dir_url(__FILE__)


    <form action="" method="post" class="income_tax_calculator">

        <?php wp_nonce_field(); ?>

            <label for="income_tax">How many charges are there?</label>
            <input type="text" name="income_tax" id="income_tax">

            <input type="submit" name="calculate_income_tax" id="calculate_income_tax" value="Calculate">




my js file:


    console.log(dataObj)   // emtpy!!!!



        var income_tax = $("#income_tax").val();

        // ajax, post, calculate.php is in plugin directory



My javascript file get empty dataObj array from php file and I don't know why. I load my javascript file after jquey, in the footer, but array is till empty. Javascript file is really found in the footer in view source code.

Generally, am I in a good way? This is my first plugin.

1 answer

  • answered 2018-05-16 13:20 Tautve

    I needed to use this:

    add_action( 'wp_footer', 'my_styles_scripts' );


    add_action( 'wp_enqueue_scripts', 'my_styles_scripts' );