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:
$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.
The resulting code should look something like this:
Make sure that the script with the handle
self::slug.'-postlister'
is enqueued before you callwp_localize_script
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