Pass parameters to javascript using wp_localize_script

I have read a half-dozen examples of how to pass parameters to javascript and they all describe the process in a very similar manner but don’t speak to one event: how does the javascript code actually get called? I have seen several examples where the code is tested in $document.ready, but can’t get them to work.

Here is my php code:

Read More
$base_id = 'id_'.wp_create_nonce("postlister");
$url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$parms = array(
    'url'       => $url,
    'action'    => $action,
    'base_id'   => base_id );
wp_localize_script(self::slug.'-postlister', 'postlister_parms', $parms);

And my jQuery code:

jQuery(document).ready(function (postlister_parms) {
    if (postlister_parms !== undefined) {
        var parms = postlister_parms;
        $.diagnostic('postlister loaded');
    }
});

When the page loads, there is a div generated were my code writes some additional html:

    echo '<div id="'.$base_id.'"></div>';

produces:

<div id="id_c8aca14643"></div>

The footer contains:

<script type="text/javascript" src="http://localhost/mkpusa.org/nw/wp-content/plugins/rhj4-postlister/js/postlister.js?ver=3.9.2"></script>

When the jQuery code executes, postlister_parms is a function:

postlister_parms: function (a,b){return new n.fn.init(a,b)}

But postlister_parms.url, .action and .base_id are all undefined.

Please help me spot what I am missing.

Related posts

Leave a Reply

2 comments

  1. The resulting code should look something like this:

    var postlister_parms = {"url":"the_url","action":"the_action","base_id":"the_baseid"};
    

    Make sure that the script with the handle self::slug.'-postlister' is enqueued before you call wp_localize_script

  2. Have you read the Notes section of the documentation The call to wp_enqueue_script and wp_localize_script should be in a wp_enqueue_scripts action and the script should be enqueued before it is localized. That being true, it should work