How to include admin-ajax when loading external javascript

What you need to do is register and/or enqueue your script and then use wp_localize_script to include a Javascript variable on your page. The Codex page has this example:

wp_enqueue_script( 'some_handle' );
$translation_array = array( 
    'some_string' => 
    __( 'Some string to translate' ), 
    'a_value' => '10' 
);
wp_localize_script( 'some_handle', 'object_name', $translation_array );

You can then access the variable with, to quote the same Codex page:

<script>
alert(object_name.some_string); // alerts 'Some string to translate'
</script>

Leave a Comment