Pass parameters to javascript using wp_localize_script - javascript

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:
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

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

Related

getJSON is not a function when the second time I called it

This is the first time I use jquery. The situation I'm facing here is that I need to parse some JSON file whose url is given by another JSON file.
Thus, I use the code
var GlobalID = {};
function parseID() {
var data;
$.getJSON('https://taitk.org/api/algorithms', function(algorithms) {
GlobalID = algorithms;
console.log("ID got!");
parseKeyword();
});
}
function parseKeyword () {
for(var i = 0; i < GlobalID.length; i++) {
$.getJSON('https://taitk.org/api/algorithms/' + GlobalID[i].id, function(subdata) {
console.log(subdata.data)
});
}
}
, where parseID() is a function to get the ID of each url, parseKeyword() is a function print out each url's data (written in the callback function, thus avoid the asynchronous function call).
However, the error I got is keyword.js:31 Uncaught TypeError: $.getJSON is not a function while the message "ID got!" is successfully printed. Also, the code work fine when I delete the parseKeyword()function, which is confusing for me because the first getJson() call seems to work while the second doesn't.
I'd like to figure out what kind of situation I'm facing to cause such error, thank you.
And, below is how I include those function in the html file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script></script>
<script src="js/keyword.js"></script>
<script type="text/javascript">
parseID()
</script>
The real cause is that I included the slim version of jquery in the <body> part along with the version mentioned in the question description. After removing it, it seems good.

Error Call Function On Yii2 Dropdown Active Form

Halo, I using Yii2 and I get error while call a function in dropdown list.
This is my dropdown :
<?= $form->field($model, "jenis_manifest")->dropDownList([ 'Berangkat' => 'Berangkat', 'Pulang' => 'Pulang'], ['onchange' => 'fungsiUtama();', 'class' => 'form-control', 'prompt' => '-- Manifest --']) ?>
And this is my script :
<?php
$script = <<<JS
function fungsiUtama()
{
alert("Hello");
}
JS;
$this->registerJs($script);
?>
I also try with JsExpression base on this question, but still not working.
This is the error what I get :
Use
$this->registerJs($script, \yii\web\View::POS_END);
The last part means - add this script straightforward at the end of page.
Without the second function argument the default one is called -
\yii\web\View::POS_READY - which means - add this script wrapped in jQuery(document).ready() method that forces scripts to wait untill the page's DOM is fully loaded. Before that your script is unavailable and that is probably why you've got this error.

PHP minify function seems to destroy inline JS?

I have the following minify function:
public static function minify($buffer)
{
$search = array(
'/\>[^\S ]+/s',
'/[^\S ]+\</s',
'/(\s)+/s'
);
$replace = array(
'>',
'<',
'\\1'
);
$buffer = preg_replace($search, $replace, $buffer);
return $buffer;
}
This function is used with ob_start() in order to minify my html output. The function is taken from here: https://stackoverflow.com/a/6225706/4601581
This function seems to destroy some of my JS. Example: A button i click to execute some JS:
<button type="button" class="btn btn-<?= Config::$ELEMENT_COLOR ?> btn-block" onclick="addLastInput(<?= $mask->getId() ?>)">Do it</button>
The $id i give to addLastInput is simply a number, taken from $mask->getId().
Also i have this little JS code to populate some data array:
<script>lastSubmissionData[<?=$mask->getId()?>] = '<?=json_encode($lastSubmissionData)?>';</script>
And finally my JS function i actually want to execute with my given param (the id) and on the data array:
function addLastInput(maskId) {
var data = lastSubmissionData[maskId];
for (var i = 0; i < data.length; i++) {
// TODO
}
}
Whenever i only load the page, it simply tells me Uncaught SyntaxError: Unexpected end of input in the Chrome console. Whenever i do so with not using the minify function and outcommenting the ob_start() completely, it just works and i can use it.
Conclusion: The minify function seems to brake my inline JS as the comments on the linked SO answer suggest. Question: How can i fix that? I even googled for other minify solutions like this one: https://gist.github.com/tovic/d7b310dea3b33e4732c0
All of them seem to not work by just breaking my site. What's the best solution here to simply let me use my JS code and still minify my html output?
Don't use this minify() function. It's broken.
This function ends up removing some semantically meaningful newlines in inline Javascript code, such as ones appearing at the end of a single-line comment. (For example, it converts your example Javascript function to a single line ending in { // TODO } }.)
This function will break some HTML constructs as well. In particular, it will destroy the content of <pre> tags, as it does not recognize that whitespace is significant in that context.
(Both of these caveats are mentioned in highly upvoted comments on the post you got this code from, by the way!)

How to add external <script> to <head> section for all mediawiki pages?

I want add external script to head section for all pages in mediawiki.
Function onBeforePageDisplay callback from BeforePageDisplay hook:
//LocalSettings.php
...
# Assign my functions to hook
$wgHooks['BeforePageDisplay'][] ='onBeforePageDisplay';
function onBeforePageDisplay( OutputPage &$out, Skin &$skin )
{
mw.loader.load('http://static.wowhead.com/widgets/power.js', 'text/javascript');
$out->addModules( 'mw.loader' );
return true;
};
In this function i want to add
<script type="text/javascript" src="http://static.wowhead.com/widgets/power.js"></script>
<script>var wowhead_tooltips = { "colorlinks": true, "iconizelinks": true, "renamelinks": true }</script>
to <head> section for all pages in wiki.
For old versions of mediawiki used addScript method of OutputPage object:
$out->addScript( $html )
// Add a JS file. $html is a full script tag: '<script type="text/javascript" src="..."></script>'
but now
For MediaWiki 1.17 and above, use ResourceLoader modules.
$out->addModules( array( /modules/ ) );
I could not make it work and don't find any examples of this.
ResourceLoader description
Default_modules description
Maybe I have to use mw.loader.load module, but I have no idea how to do it. Help me, please, and sorry for my english.
P.s. this solution work, but is not right. Need solution with used ResourseLoader. (c)IMHO
Solution was simple (it looks like 2nd solution):
//LocalSettings.php
...
# Assign my functions to hook
$wgHooks['BeforePageDisplay'][] ='onBeforePageDisplay';
function onBeforePageDisplay( OutputPage &$out, Skin &$skin )
{
$script = '<script type="text/javascript" src="http://static.wowhead.com/widgets/power.js"></script><script>var wowhead_tooltips = { "colorlinks": true, "iconizelinks": true, "renamelinks": true }</script>';
$out->addHeadItem("wowhead script", $script);
return true;
};
This way look better then this, because it work with OutputPage directly (after parsing).

Jquery and javascript namepsace

In trying to namespace my js/jquery code, I have come up against the following problem.
Basically, I used to write all my JS code in each html/php file, and I want to abstract that away to a single js file with namespaces.
So, in my html file I have:
<script type="text/javascript">
$(document).ready(productActions.init());
</script>
And in my js file I have:
var productActions = {
init: function() {
alert('initialsed');
$('#field_id').change(function() {
alert('ok!');
});
}
The productActions init function is definitely running, because I get the first alert (initialised). However, it seems that none of the jquery binding functions do anything at all. Stepping through the init function shows that the above change function is being registered, but actually changing the value in the field does absolutely nothing.
Am I missing something obvious here?
$(document).ready(productActions.init());
This code calls init() immediately and passes its return value to ready(...). (just like any other function call)
Instead, you can write
$(document).ready(productActions.init);
To pass the function itself. Howeverm this will call it with the wrong this; if you need this, write
$(document).ready(function() { productActions.init() });

Categories