How to pass php variables to javascript

While developing an ajax-based plugin, you’ll often find yourself in situations where you have to pass some PHP variables to Javascript. This can be a pain especially when your plugin grows.

Luckily, WordPress provides a way to simplify the process drastically.

Here is an example:

wp_enqueue_script('your-js-handler-name', plugins_url('assets/js/some.js', __FILE__), array('jquery'), false, true);

$data = array(
                'ajaxurl' => self_admin_url('admin-ajax.php'),
                'number' => 1,
                'array' => array('I', 'am', 'a', 'wordpress', 'plugin', 'developer')
            );

wp_localize_script('your-js-handler-name', 'EXAMPLE', $data);

Right now, you can access the $data variables in javascript via EXAMPLE.ajaxurl

Share and Enjoy

    FacebookTwitterGoogle PlusLinkedInStumbleUponPinterestRedditTumblrDiggEmailPrint

Related Posts