Retrieve value of a Jquery variable name containing a variable in itself - javascript

In the top of my Jquery I've got many variables (associated with values) called : files_1, files_2, etc.
They are created in a script, in the bottom of my page :
<script>
$(function () {
<?php foreach ($folders as $f) { ?>
var files_<?=$f['request_id']?> = 0;
<?php } ?>
…
});
</script>
In my html I've got a link like :
Delete
data-request-id parameter gives me a number, the ones you've got in my variables names on top. In my example, it's data-request-id="2" : files_2.
Next, I've got a Jquery function that catch data values from links :
$('.request-files').on('click', 'a.delete', function (e) {
e.preventDefault();
var $link = $(this);
var $id = $link.data('request-id');
console.log(files_$id); // <-- It doesn't work
});
What I need to do is to retrieve the value of the variables files_x. In my example, I tried to get them using files_$id but it doesn't work.
Any idea ?

If you have your variables defined in the global scrope, they are attached to the window object. So you should be able to access your variables by using bracket notation on the window object:
$('.request-files').on('click', 'a.delete', function (e) {
e.preventDefault();
var $link = $(this);
var $id = $link.data('request-id');
console.log(window['files_' + $id]); // <-- It DOES work
});
UPD: your variables are in the closure of document.ready function ($(function() {...});), so you won't be able to access them from other scopes. I assume that your click handler is within that closure as well. I can suggest creating a separate object with properties named file_<ID> - it will work much alike as with window:
<script>
$(function () {
var filesMap = {};
<?php foreach ($folders as $f) { ?>
filesMap['files_' + <?=$f['request_id']?>] = 0;
<?php } ?>
…
$('.request-files').on('click', 'a.delete', function (e) {
e.preventDefault();
var $link = $(this);
var $id = $link.data('request-id');
console.log(filesMap['files_' + $id]);
});
});
</script>
I am not familiar with PHP, so the string concatenation in request_id part might be different, but the logic remains.

Related

Call script inside if statement Wordpress

Im trying to conditionally call script depending of language in Wordpress with polylang. I can see the script in Google Inspector but it doesn't work. Script works correctly in customizer.
Code:
<?php
if(pll_current_language() == 'en') : ?>
<script type="text/javascript">
const cartBtn = document.querySelector('.cart button');
const formCart = document.querySelector('div.product.elementor form.cart');
var newBtn = document.createElement('a');
newBtn.innerHTML = "<h1>Back to shop</h1>";
newBtn.classList.add('cart-custom-link');
newBtn.setAttribute("href", "/shop/");
cartBtn.addEventListener('click', function() {
formCart.appendChild(newBtn);
console.log('click');
});
</script>
<?php endif; ?>
<?php
if(pll_current_language() == 'uk') : ?>
<script type="text/javascript">
const cartBtn = document.querySelector('.cart button');
const formCart = document.querySelector('div.product.elementor form.cart');
var newBtn = document.createElement('a');
newBtn.innerHTML = "<h1>Повернутися до магазину</h1>";
newBtn.classList.add('cart-custom-link');
newBtn.setAttribute("href", "/shop-uk/");
cartBtn.addEventListener('click', function() {
formCart.appendChild(newBtn);
console.log('click');
});
</script>
<?php endif; ?>
Is there any solution?
My assumption why the code does not work is because the script code is added (and therefore run) before the DOM tree is ready. Thus, it has to be wrapped in a window.onload handler (or jQuery's $(document).ready();). Also, copy&pasting the JS code for every language isn't really pretty. There's a cleaner solution:
place the code in a .js-file
use a JS-object for the text to be translated
enqueue the script, then use wp_localize_script() on it
like so:
my_cart.js
window.onload = function () {
const cartBtn = document.querySelector('.cart button');
const formCart = document.querySelector('div.product.elementor form.cart');
var newBtn = document.createElement('a');
newBtn.innerHTML = "<h1>"+cart_localize.back_to_shop+"</h1>";
newBtn.classList.add('cart-custom-link');
newBtn.setAttribute("href", "/shop-uk/");
cartBtn.addEventListener('click', function() {
formCart.appendChild(newBtn);
console.log('click');
});
}
Next, within PHP, enqueue the script like so:
function load_localized_scripts() {
$cart_localize = array(
'back_to_shop' => 'Back to shop', // default
);
if (pll_current_language() == 'uk') {
$cart_localize['back_to_shop'] = 'Повернутися до магазину';
}
if (pll_current_language() == 'de') {
$cart_localize['back_to_shop'] = 'Zurück zum Shop';
}
wp_enqueue_script('my-cart', plugin_dir_url( __FILE__ ) . 'js/my_cart.js');
wp_localize_script('my-cart', 'cart_localize', $cart_localize);
}
add_action('wp_enqueue_scripts', 'load_localized_scripts');
The $cart_localize array may contain as many key → value pairs of label => text translation as you like. It is inserted into the JavaScript object named like the 2nd argument of the wp_localized_script function. Then, you can access it within JS using cart_localize.key_name.
Technically, you can also register a Polylang string using pll_register_string named back_to_shop and easily insert the translations you entered under Languages → String translations using the pll__() function:
$cart_localize['back_to_shop'] = pll__('back_to_shop');
I won't fully cover this here, since I'm not sure this matches the way you want to manage translations.

How to pass value from on javascript to another javascript file when I pass value in function?

Generate ID
Above is my php code from where I pass id value in a JavaScript Function
function passid(id)
{
var gener = "<script type=\"text/javascript\">
var id = "+id+"<\/script>
<script src=\"http://mySample.com/MYjs/myJS.js\"><\/script>";
document.getElementById('codegen').textContent = gener ;
}
from this I want to pass ID in myJS.js File How to send this ID.
Why not use Jquery?
$('.generate').on('click', function () {
passid(1);
});
function passid(id) {
var gener = "<script type=\"text/javascript\">var id = "+id+";alert(id);<\/script>"+"<script>alert(id);<\/script>"+"<script src=\"alert.js\"><\/script>";//Alert inside JS file too!
$(gener).appendTo(document.body);
}
http://jsfiddle.net/LeroyRon/bk9fryuj/
///No jQuery version
Look around to here: Adding <script> element to the DOM and have the javascript run?
Just make id global variable and to change html you need to use innerHTML:
function passid(id) {
window.id = id;
var gener = "<script src=\"http://mySample.com/MYjs/myJS.js\"><\/script>";
document.getElementById('codegen').innerHTML = gener;
}

Sending multiple GET variables in URL with Javascript

I'm trying to retrieve multiple $_GET variables within PHP. Javascript is sending the URL and it seems to have an issue with the '&' between variables.
One variable works:
//JAVASCRIPT
var price = "http://<site>/realtime/bittrex-realtime.php?symbol=LTC";
//THE PHP END
$coinSymbol = $_GET['symbol'];
echo $coinSymbol
OUTPUT: LTC
With two variables:
//JAVASCRIPT
var price = "http://<site>/realtime/bittrex-realtime.php?type=price&symbol=LTC";
//THE PHP END
$coinSymbol = $_GET['symbol'];
$type = $_GET['type'];
echo $coinSymbol
echo $type
OUTPUT: price
It just seems to ignore everything after the '&'. I know that the PHP end works fine because if I manually type the address into the browser, it prints both variables.
http://<site>/realtime/bittrex-realtime.php?type=price&symbol=LTC
OUTPUT ON THE PAGE
priceLTC
Any ideas? It's driving me nuts - Thanks
UPDATE - JAVASCRIPT CODE
jQuery(document).ready(function() {
refresh();
jQuery('#bittrex-price').load(price);
});
function refresh() {
setTimeout( function() {
//document.write(mintpalUrl);
jQuery('#bittrex-price').fadeOut('slow').load(price).fadeIn('slow');
refresh();
}, 30000);
}
Separate the url and the data that you will be sending
var price = "http://<site>/realtime/bittrex-realtime.php";
function refresh() {
var params = {type:'price', symbol: 'LTC'};
setTimeout( function() {
//document.write(mintpalUrl);
jQuery('#bittrex-price').fadeOut('slow').load(price, params).fadeIn('slow');
refresh();
}, 30000);
}
And in your PHP use $_POST or you can do it like this
$coinSymbol = isset($_POST['symbol']) ? $_POST['symbol'] : $_GET['symbol'];
Refer to here for more information jquery .load()

concat two strings in JQuery

Just like the title above: how to concatenate two strings in JQuery?
This is my code so far:
$(document).ready(function(){
serviceName = '<?=$_GET['services'] . ".php";?>';
serviceID='<?= "#" .$_GET['services'];?>';
serviceClass = '<?=$_GET['services'];?>';
if (serviceName != "") {
alert(serviceID);
$('.main_content').load(serviceName);
$(serviceID).addClass("it");
}
});
As you can see in my above code, in variable name serviceID, I am concatenating hashtag and my GET value and I try to put it on ALERT and the result is correct, but when I assign it to .addClass it’s not working.
Any alternatives and solution is much appreciated.
I guess you meant that the PHP code should be evaluated before arriving to the client, therefore your code syntax is correct, but check out the following looks cleaner and also not polluting the global JavaScript scope (that's what the var ... is for):
var serviceClass = '<?="{$_GET["services"]}";?>';
var serviceName = serviceClass+'.php';
var serviceId = '#'+serviceClass;
but, since your code syntax is correct, you should verify that you actually have an element with serviceId as the id when your are executing it
if (($(serviceId)||[]).length) {
alert('your element with the id:'+serviceClass+' exists');
}
else {
alert('your element with the id:'+serviceClass+' doesn\'t exists');
}
i hope this one solve the issue:
<script>
$(document).ready(function(){
serviceName = '<? echo "./".$_GET["services"].".php";?>';
serviceID = '<? echo "#" .$_GET["services"]; ?>';
serviceClass ='<? echo $_GET["services"]; ?>';
console.log(serviceID);
if(serviceName!=""){
alert(serviceID);
$('.main_content').load(serviceName);
$(serviceID).addClass("it");
}
});
</script>
also check the console in your browser (firebug or chrome developer tools) to see the output ,fit your criteria
Try as but not sure, My change is append "#" Id in jquery
<script>
$(document).ready(function(){
serviceName = '<?=$_GET['services'] . ".php";?>';
serviceID='<?= $_GET['services'];?>';
serviceClass = '<?=$_GET['services'];?>';
if(serviceName!=""){
alert(serviceID);
$('.main_content').load(serviceName);
$("#"+serviceID).addClass("it");
}
});
</script>

Javascript function fails with global vars

I have used this function to submit to any url or 'self',
with or without a querystring, many times without any problems.
function submitu(url, q) {
var frm = document.<?php echo $formname ?>;
if (url == '') {url = '<?php echo $thispage?>'; }
frm.action = url+q; frm.submit(); }
If I try to move the PHP vars outside the function, as below, it stops working (frm undefined error)
var thispage = '<?php echo $thispage?>';
var frm = document.<?php echo $formname?>;
function submitu(url, q) {
if (url == '') {url = thispage;}
frm.action = url+q; frm.submit();}
I also tried var frm = document.forms[''];
I don't have any other conflicting javascript,
(1). Can anyone tell me why this is not working?
(2). And why the first method also fails if the function is placed
inside and at the top of the jquery $(function() {.....} ready function?
Many thanks
It fails because when outside the function, var frm = document.formname;
will be run immediately when the page loads, i.e. before the form element has actually been constructed, so you get 'undefined'. When inside the function, it is only run when the function is run, by which time the DOM is complete and it can find it.

Categories

Resources