1) Register or Enqueue your script.
2) Localize your script.
We have found some caveats for some themes. Most importantly, make sure you select for “late loading” or “load in footer” so the script can be localized BEFORE it is rendered in the browser. The other option is to register the script using wp_register_scripts() in the wp_enqueue_scripts hook then later load the script in a wp_footer hook using wp_enqueue_scripts(). Just keep in mind that not all themes support wp_footer().