How to add var javascript value into id name? - javascript

How to add var javascript value into id name ?
I have $i = 5; and var i = 2;
How to concatenate php var $i with javascript var i ?
I tried like this but not work.
$('#test<?PHP echo $i; ?>'+i).live('click', function() {
do something
});
and
$('#test<?PHP echo $i; ?>'+i+'').live('click', function() {
do something
});
How can i do that ?

var phpi = '<?PHP echo $i; ?>';
$('#test' + phpi + i).live('click', function() {
//do something
});
or if you want PHP $i + JS i for exmaple (3 + 2 = 5)
var phpi = <?PHP echo $i; ?>; // no quotes here as we need number
$('#test' + (phpi + i)).live('click', function() {
//do something
});
PHP echo makes some space so that might hamper the selector use it like this

Related

JQuery fails to load when i use a php variable

I'm incorporating PHP code into JQuery like this:
echo "<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
var count = ($('.data').length + 25);
/* This is the line */var c = $c;
$('#data').load('data.php?v=' + count + '&c=' + c)
$('.btn-data').click(function() {
count = count + 25;
$('#data').load('data.php?v=' + count + '&c=' + c)
})
})</script>";
The PHP variable shows as blue, there are no errors showing, but when I run it it refuses to work. I've tested everything else and I'm 100% sure PHP is the one causing the problem.
How can I fix this?
If $c is your php variable you will need to quote and join it inside an echo tag.
But as Carton (+1) said, is it a string, integer, object?
If it's an integer, this should work...
<?php
echo "<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
var count = ($('.data').length + 25);
var c = " . $c . ";
$('#data').load('data.php')
$('.btn-data').click(function() {
count = count + 25;
$('#data').load('data.php?v=' + count + '&c=' + c)
})
});
</script>";
If it's a string this should work...
<?php
echo "<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
var count = ($('.data').length + 25);
var c = '" . $c . "';
$('#data').load('data.php')
$('.btn-data').click(function() {
count = count + 25;
$('#data').load('data.php?v=' + count + '&c=' + c)
})
});
</script>";
If it's an object, you will have to parse the var or encode it.
Sometimes if you want to echo or return big blocks of html inside php, you can use an output buffer to capture the html, and then you can either return the html via a function, or echo it. This just makes your html easier to read when it's not wrapped inside echo quotes tags.
<?php
// c sting php var
$c = 'string';
// start output buffer
ob_start();
?>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
let count = ($('.data').length + 25);
let c = '<?=$c?>';
$('#data').load('data.php');
$(this).on('click', '.btn-data', function() {
count = count + 25;
$('#data').load('data.php?v=' + count + '&c=' + c);
});
});
</script>
<?php
// store everything between ob_start() and here into a php variable
$script = ob_get_clean();
// return script html
return $script;
// or echo script html
echo $script;
// not both together obviously
?>

Call PHP function inside JavaScript inside echo

I have read the other similar questions, but not found the answer, so here it is:
<?php
function load($page) {
echo "page: ".$page;
}
echo "
<script type='text/javascript'>
var page = 0;
window.addEventListener(...., function(){
var x = .....
......
if(x = ....)
{
page = page + 1;
var runQuery = '<?php load(page); ?>'
}
})
</script>
";
?>
The problem is that <?php load(page); ?> is not executed. If I write load(page); outside the echo, it works. Can anyone help me ?
Change the function to return:
function load($page) {
return "page: ".$page;
}
You're executing PHP with the echo so just use the return of load():
echo "
<script type='text/javascript'>
var page = 0;
window.addEventListener(...., function(){
var x = .....
......
if(x = ....)
{
page = page + 1;
var runQuery = '" . load($page) . "'
}
})
</script>
";

Php Counter Hides Comma after loading and not showing permanently

I am trying to figure out a php counter. I have added Number format in a php function to print counter digits separated with a comma after first 3 digits. But Comma doesn't show up permanently after page load, When I reload the page, Comma shows for a moment but immediately hides. Below is the code i have used to get this result and please review the counter page.
<?php
$bg = get_field('counter_bg');
$init_value = get_field('init_value');
$init_date = get_field('init_date');
$seconds = strtotime("now") - strtotime($init_date);
$countup_value = get_field('countup_value');
$number = round((($seconds * $countup_value) + $init_value) * 100) / 100;
if($number) :
$title = get_field('counter_title');
$text = get_field('counter_text');
?>
<section class="home-section" id="home-counter" <?php if($bg['url']) echo "style='background-image: url({$bg['sizes']['slide-thumb']})'"; ?>>
<div class="container">
<?php
if($title) echo "<h3 class='counter-title'>{$title}</h3>";
echo "<div id='counter-number'>";
echo Number_format ($number);
echo "</div>";
if($text) echo "<div class='counter-text'>{$text}</div>";
?>
</div><!--containr-->
</section><!--home-section-->
<script>
(function($) {
$(document).ready(function(){
var counter = $('#counter-number');
var coutUp = Number(<?= $countup_value ?>);
setInterval(function() {
counter.text(calculate_value);
}, 1000)
function calculate_value() {
var initDate = moment('<?= $init_date ?>').format('x');
var nowDate = moment().format('x');
var dif = Number((nowDate - initDate) / 1000);
var value = Number(dif * coutUp);
// console.log(initDate, nowDate, dif, value, '<?= $init_date ?>');
return value.toFixed(2)
}
});
})(jQuery);
</script>
<?php endif; ?>
Please check the current Comman display issue at: http://airlite.designase.com/it/
According to the php number_format, you want to group the number by thousands. You can to that by changing the return of the calculate_value function like this:
return value.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
The regex will add a comma every 3 digits, like this:
(function($) {
$(document).ready(function(){
var counter = $('#counter-number');
var coutUp = Number(1);
setInterval(function() {
counter.text(calculate_value);
}, 1000)
function calculate_value() {
var initDate = moment(20111031).format('x');
var nowDate = moment().format('x');
var dif = Number((nowDate - initDate) / 1000);
var value = Number(dif * coutUp);
// console.log(initDate, nowDate, dif, value, '<?= $init_date ?>');
return value.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
});
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="counter-number"></span>
Now it should keep the comma. You can set the number of decimals by changing the (2) parameter in toFixed() function in the end of the JS function.
<?php
$bg = get_field('counter_bg');
$init_value = get_field('init_value');
$init_date = get_field('init_date');
$seconds = strtotime("now") - strtotime($init_date);
$countup_value = get_field('countup_value');
$number = round((($seconds * $countup_value) + $init_value) * 100) / 100;
if($number) :
$title = get_field('counter_title');
$text = get_field('counter_text');
?>
<section class="home-section" id="home-counter" <?php if($bg['url']) echo "style='background-image: url({$bg['sizes']['slide-thumb']})'"; ?>>
<div class="container">
<?php
if($title) echo "<h3 class='counter-title'>{$title}</h3>";
echo "<div id='counter-number'>";
echo Number_format ($number);
echo "</div>";
if($text) echo "<div class='counter-text'>{$text}</div>";
?>
</div><!--containr-->
</section><!--home-section-->
<script>
(function($) {
$(document).ready(function(){
var counter = $('#counter-number');
var coutUp = Number(<?= $countup_value ?>);
setInterval(function() {
counter.text(calculate_value);
}, 1000)
function calculate_value() {
var initDate = moment('<?= $init_date ?>').format('x');
var nowDate = moment().format('x');
var dif = Number((nowDate - initDate) / 1000);
var value = Number(dif * coutUp);
// console.log(initDate, nowDate, dif, value, '<?= $init_date ?>');
return value.toFixed(2).replace(".", ",")
}
});
})(jQuery);
</script>
<?php endif; ?>

How to pass a PHP array to another PHP page with ajax

I have been looking for this answer without success.
I have three files: index.php, actions.js and devices.php
My index.php have this code:
<?php
$file = "canvas/interactiveWorkstations/".$roomData['id'].".json";
if(file_exists($file)){
$map = "interactiveWorkstation";
$lines = file($file);
$nPolygon = $lines[count($lines) - 4];
$counterPolygon = 0;
$pos = 4;
$areas = array();
while($counterPolygon !== $nPolygon && $pos < count($lines)){
$lines[$pos] = json_decode($lines[$pos], true);
if($counterPolygon !== 0)
$lines[$pos] = array_diff_assoc($lines[$pos], $lines[$pos-9]);
$coords = "";
foreach($lines[$pos] as $line)
foreach($line as $k => $v)
if($k !== "color" && $v !== -1)
$coords .= $v . ", ";
$coords = trim($coords, ', '); //Delete last space and last comma
$lines[$pos-3] = trim($lines[$pos-3], '#');
$areas[trim($lines[$pos-3])] = $coords;
$counterPolygon++;
$pos = $pos + 9;
}
?>
<script>
var img = document.getElementsByClassName('connection')[0];
img.setAttribute('usemap', '<?php echo "#".$map; ?>');
img.insertAdjacentHTML('afterend', '<map name="<?php echo $map; ?>" id="<?php echo $map; ?>"></map>');
var points = <?php echo json_encode($areas);?>;
</script>
<?php
}
if($bookingActive) {
echo '<script type="text/javascript">reloadDevices("'.$workstationName.'","'.$randomKey.'","'.$bookingData['ical_uid'].'",points); initCountdown('.$remainingTime.');</script>';
}
At this point I have passed my $areas variable to JS using json_encode, and my functions reloadDevices() and UpdateDevices() receive it correctly because I checked before.
In my actions.js file have this code:
function updateDevices(workstation,randomKey,z,points){
var parameters = {
"workstation" : workstation,
"randomKey" : randomKey,
"z" : z,
"points" : points
};
$.ajax({
data: parameters,
url: 'workstation/devices.php',
type: 'post',
success: function (response) {
$("#devices").html(response);
}
});
}
function reloadDevices(workstation,randomKey,z,points) {
updateDevices(workstation,randomKey,z, points);
setInterval(function () { updateDevices(workstation,randomKey,z, points); }, 6000);
}
I do an ajax call to devices.php, but when I wanna get my $_POST['points'] variable is empty.
The part of code from my devices.php where I use this variable:
<?php
$areas = json_decode($_POST['points'], true);
?>
<script>
var map = document.getElementById('interactiveWorkstation');
var area = document.getElementById('<?php echo $deviceName; ?>');
if(!area)
map.insertAdjacentHTML('beforeend', '<area id="<?php echo $deviceName; ?>" shape="polygon" coords="<?php echo $areas[$deviceName]; ?>" href=\'javascript:createTerminal(<?php echo "\"".$deviceName."\""; ?>, <?php echo "\"".$deviceIp; ?>-<?php echo $randomKey."\""; ?>, <?php echo "\"".$uid."\""; ?>, <?php echo "\"".$deviceName."\""; ?>);\'/>');
</script>
Honestly, I can't see the error. If someone helps me appreciate it.
Thanks so much.
Regards.

Three.js : change texture at runtime

I'm creating an UI in which the user will be able to change the texture of the selected object by clicking on the desired textures picture.
The problem is that I can only use the last texture added in the array.
Here is my php which lists the textures in my specified folder:
<ul id="textureH">
<script type="text/javascript">
texArray = [];
</script>
<?php
for($index=0; $index < $indexCount; $index++) {
$extension = substr($dirArray[$index], -3);
if ($extension == 'jpg'){
$texName = $dirArray[$index];
$texId = "texture". $index;
?>
<script type="text/javascript">
var texName = '<?php echo $texName ?>';
var texId = '<?php echo $texId ?>';
texArray.push(texId);
</script>
<?php
echo "<li id='".$texId."'><table><tr><td><img class='texture-image-list' src='img/" . $texName . "' alt='Image' /></td><td><span id='texture-item-name'>" . $texName . "</span></td></tr></table></li>";
}
}
?>
</ul>
And here's my function:
var uTexture = document.getElementById(texId);
uTexture.addEventListener("click", updateTexture, false);
function updateTexture(){
var texMap = "./img/" + texName;
for (var i in texArray) {
if ((texArray[i] == texId) && (SELECTED instanceof THREE.Mesh)) {
SELECTED.material.map = THREE.ImageUtils.loadTexture(texMap);
SELECTED.material.needsUpdate = true;
}
}
}
I think the problem comes from the array.
Thanks to 2pha I could achieve what I wanted to do.
Here's my new code:
(The php/html)
<div class="right-panel-textures">
<h3 id="cat-hierarchy">Textures</h3>
<?php
$myDirectory = opendir('img/textures');
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
sort($dirArray);
closedir($myDirectory);
$indexCount = count($dirArray);
?>
<ul id="textureH">
<?php
for($index=0; $index < $indexCount; $index++) {
$extension = substr($dirArray[$index], -3);
$texName = $dirArray[$index];
$texId = "texture". $index;
if ($extension == 'jpg'){
?>
<script type="text/javascript">
var texName = '<?php echo $texName ?>';
var texId = '<?php echo $texId ?>';
</script>
<?php
echo "<li class='texture-single-item' data-texture-name='".$texName."' data-texture-id='".$texId."' id='texture-single-item'><table><tr><td><img class='texture-image-list' src='img/textures/" . $texName . "' alt='Image' /></td><td><span id='texture-item-name'>" . $texName . "</span></td></tr></table></li>";
}
}
?>
</ul>
</div>
(And the JavaScript)
var uTexture = document.getElementById("texture-single-item");
uTexture.addEventListener("click", updateTexture, false);
function updateTexture(){
$(".texture-single-item").bind("click", function(event) {
var nameT = $(this).attr("data-texture-name");
if (SELECTED instanceof THREE.Mesh) {
var texMap = "./img/textures/" + nameT;
SELECTED.material.map = THREE.ImageUtils.loadTexture(texMap);
SELECTED.material.needsUpdate = true;
}
});
}
Thank you :)

Categories

Resources