1

I'm using Bitbucket and have Scrutinizer configured to analyze code when uploaded. It complains about a variable not being declared and it causes a hit on code grading.

The variable txtVars seems to be never declared. If this is a global, consider adding a /** global: txtVars */ comment.

This makes sense to me as I am using the variable in my jQuery without it being declared in any way except for in my WordPress functions.php file:

txtVars is introduced with the following PHP:

wp_enqueue_script( 'my-script', 
                   MY_URL . 'assets/js/public.js', 
                   array('jquery', 'heartbeat'), 
                   MY_VERSION, 
                   true 
);

$vars = array(
        'confirm_submit'       => __( 'Submit', 'textdomain' ),
        'confirm_cancel'       => __( 'Cancel', 'textdomain' )
    );

wp_localize_script( 'my-script', 'txtVars', $vars );

This allows me to use txtVars in the jQuery script:

confirm(txtVars.confirm_submit);

I've tried declaring txtVars a few different ways within the jQuery but it doesn't help, it generates an error, or txtVars ends up empty.

Is there a way to declare this variable in jQuery to satisfy code checkers that expect variables to be declared?

random_user_name
  • 25,694
  • 7
  • 76
  • 115
rwkiii
  • 5,716
  • 18
  • 65
  • 114
  • Placing the comment above the jQuery resolved the problem. I was placing it within the jQuery. If you want to write up an answer I'll mark it correct. Seems stupid to me that I didn't try this. Thanks. – rwkiii Sep 13 '16 at 22:02

1 Answers1

1

I believe that the error message is telling you more or less what needs to happen, but sometimes the details (such as placement in the file) can be elusive.

In order to solve this, at the top of your script file, even before your jQuery, add this comment:

/** global: txtVars */
random_user_name
  • 25,694
  • 7
  • 76
  • 115