How to parse a PHP variable using a dynamic JS variable? - javascript

I have 5 PHP variables, $menu1 to $menu5, that each evaluate to a keyword. I'm trying to populate these 5 PHP variables in JavaScript, and display them. The below code doesn't work. What is wrong with my processing of the PHP variables?
var menu_populator = "";
for (var x = 1; x <= count; x++) {
menu_populator += '<li><a class="myclass" href="#link">' + '<?php echo $menu' + x + '?>' + '</a></li>';
}
$('#nav_menu').html(menu_populator);

Depending on how you are getting the menu data server-side you can try both methods below. One is for set $menu variables but if you are getting data from a database or the $menu variable are created within a loop you might find the second method better.
Method one- PasteBin
Echo your php variables into a javascript array.
var myarray=["<?php echo $menu1;?>","<?php echo $menu2;?>","<?php echo $menu3;?>","<?php echo $menu4;?>","<?php echo $menu5;?>"];
Method Two- PasteBin
Create this array server-side, this will be better if you are creating the current $menu variable in a loop, with this you can just use array_push() to push the values into the array.
<?php
// PHP Array
$menu = array('Home', 'Gallery', 'About');
// How to push new item into array
array_push($menu, 'Contact');
?>
Then just simply echo this array into your javascript myarray variable.
var myarray=<?php echo json_encode($menu);?>;
I have used the following javascript to test both methods and both seem to function just fine. I prefer the second method but I have decided to offer both as I don't know what your PHP looks like or how your $menu variables are being defined so this should cover both.
window.onload=function(){
for(var i=0; i<myarray.length; i++){
var link= document.createElement('a');
link.href="#";
link.innerHTML=myarray[i];
document.body.appendChild(link);
document.body.appendChild(document.createElement('br'));
}
}
If you have any questions about the source code above please leave a comment below and I will get back to you as soon as possible.
I hope this help. Happy coding!

Something like this would do the trick
<?php
$menu = "menu";
echo '
<script>
var count = 10;
var menu_populator="";
for(var x=1;x<=count;x++)
{
menu_populator += \'<li><a class="myclass" href="#link">'.$menu.' \'+x+\'</a></li>\';
}
$(\'#nav_menu\').html(menu_populator);
</script>
';
?>

Related

javascript variable to php array

I've made this code here and done some research and still have no idea how to insert javascript variable into php array. Is it possible, acctually?
<script>
$(document).ready(function(){
var count = 1;
var id = 1;
$("#b").click(function(){
for(i = <?php echo $row; ?>; i > 0; i--){
$("#main").prepend('<div id="first'+count+'"></div>');
count++;
}
count = 1;
for(i = <?php echo $row; ?>; i > 0; i--){
$('#first'+count+'').text('<?php echo $row['']; ?>'+count+'');
count++;
id++;
}
});
});
</script>
I wanted to put this "id" variable into $row[''].
Thanks for help.
store $row count value in hidden text and get the value onclick
It depend by what exactly you want to do but you can do it in some way.
The Javascript code can do an XMLHttpRequest to the PHP page with an url like: /page.php?my_array_name[]=my_value_1&my_array_name[]=my_value_2
So in the php page you get an array inside $_GET['my_array_name'] with the variables passed by Javascript and you can send text back to use from the Javascript code.

Use file_get_contents() and implode() to pass array to javascript not working

I am developing a simple image gallery which shows images and related caption.
All images are inside a directory and caption in another (as single files). A php script lists all files in both directories and pass arrays to a javascript wich change image and caption when the user press a button.
[...]
for($x = 2; $x < $lenght; $x++) {
$filesi[$x] = $imgdirectory."/".$lsi[$x];
}
for($x = 2; $x < $lenght; $x++) {
$filename = $capdirectory."/".$lsc[$x];
$filesc[$x] = file_get_contents($filename);
}
//Create array for JS
$captions = '["' . implode('", "', $filesc). '"]';
$images = '["' . implode('", "', $filesi). '"]';
?>
<script>
var captions = <?php echo $captions; ?>;
var images = <?php echo $images; ?>;
[...]
Images work properly and I can also print caption's file name instead of caption
i.e.
$filesc[$x] = $filename;
but when I use "file_get_contents()" to read file the gallery stops working.
If I echo $captions and manually set $captions with the very same output
e.g.
$captions='["first caption","second caption", "..."]';
the gallery works properly, so the array should be properly formatted...
Thank you in advance
SOLUTION
I was creating an array with two empty elements (0,1) in order to avoid ./ and ../ in file list, so I have added a +2 to the lsi index.
for($x = 0; $x < $lenght-2; $x++) {
$filesi[$x] = $imgdirectory."/".$lsi[$x+2];
}
In addition I have used json_encode, as suggested, instead of manual json encodig. The output seems to be the same but now the gallery works!
var images = <?php echo json_encode($filesi); ?>;
In JS you have to escape new lines in strings like this:
var multilineString = "this is\
just an example";
Maybe try to use trim() and str_replace() if you don't want to make it easier with json_encode().
UPDATE
Then I was wrong. Did you know that you can push items to arrays with just $array[] = 'item';?

Unable to show php variable in javascript?

I am unable to show php variable in javascript;
this is my code here:
<script type="text/javascript">
$(document).ready(function (){
var n=<?php echo json_encode($count)?>;
for(var i=0;i<n;i++){
var div = document.createElement('div');
div.className = "d5";
div.id=i+1;
document.getElementById('wrapper').appendChild(div);
<?php
$query="select * from shop_product where shop_uniqueid='$unq'";
$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
$product=$row["in_product"];
?>
var product=<?php echo $product?>;
$('#'+div.id).html(product);
<?php
}
?>
}//for loop ends
});//ready ends
</script>
here i am trying to pass var product in html() of which value is coming from php like: var product=<?php echo $product?>;
but when doing so php value is not coming in Javascript's var product.
when I pass $('#'+div.id).html("abcd"); abcd value is showing in divs.
please help me.
Compare the first place you take data from PHP and put it in JavaScript:
var n=<?php echo json_encode($count)?>;
with your attempt to assign the product value:
var product=<?php echo $product?>;
You haven't converted the data from plain text to JavaScript in the second line. Use json_encode there too.

repeat functions in jquery based on variable in php

I have a group of Images in a webpage with each one has it's own ID, all of the ID's saved in a php array. I want to write a script where it take the ID from the php array and pass it to the client side and repeat a certain jquery function for each image. Here what I did:
<script>
<? php for ($i = 0; $i < $counterPostID; $i++) {
$str = "#post".$arrID[$i]; ?>
var myvar = <? php echo json_encode($str); ?> ;
var myvar2 = myvar + " " + "#textcaption";
//functions to be repeated for each image
jQuery(myvar).mouseover(function() {
jQuery(myvar2).slideDown("slow");
}).mouseout(function() {
jQuery(myvar2).slideUp("slow");
});
<? php } ?>
</script>
The code work fine but only for the last occurrence in the loop, I want the jQuery code to be repeated for all the images. How can I do that?
Assuming $counterPostID is an array with all the ID's, you can just implode it to a selector
var selector = '<?php echo "#post" . implode(", #post", $counterPostID); ?>';
// should output something like -> '#postid1, #postid2, #postid3' ... etc
$(selector).on('mouseenter mouseleave', function() {
$('.textcaption', this).slideToggle('slow'); // use a class, not the same ID
});
This isn't working because you're overwriting your vars with each loop. You could output the entire array to javascript and loop through it client-side, but you don't have to. I would recommend giving your posts a class, and giving your #textcaption elements a class, since ids must be unique, and targeting the classes:
jQuery('.post').mouseover(function () {
jQuery(this).find('.textcaption').slideDown("slow");
}).mouseout(function () {
jQuery(this).find('.textcaption').slideUp("slow");
});
You're using the SAME ID over and over:
#post1 #textcaption
#post2 #textcaption
^^^^^^^^^^^^--- here
etc..
IDs can occur only ONCE in a DOM document. Since an ID must be unique, document.getElementById() (which is what jquery is using internally, basically) will only ever return a single DOM element, never a list. That means the FIRST id found is what will be returned/processed.
Plus, your code will generate highly repetitive JS. Why not simply pass your IDs as an array to JS, then loop on that array? e.g.
<script>
var IDs = <?php echo json_encode($arrID); ?>;
$.each(IDs, function(idx, valu) {
... do your mouseover/mouseout stuff here ..
});
</script>

adding php array values to javascript array

I have a php array and I want to add its value to a javascript array. For example I am doing it something like this.
$k_data = json_encode($k)
Thus
k_data = [2,3,4,8,9]
Now in javascript I am doing like the following
var s4 = [[]];
for(var i = 0; i<5; i++)
{
s4.push([i,$k_data[i]]);
}
plot5.series[0].data = s4;
where plot5 is jqplot graph. But this is not working, I am getting blank graph while the following thing is working
for(var i = 0; i<5; i++)
{
s4.push([i,Math.sin(i)]);
}
Where I am making mistake?
If you want to deal with the php array only, you can do this-
First, implode the array to make a comma-separated string, say $str. Just like-
<?php
$str = implode(",", $array);
?>
Then, use split to convert the php string to the javascript array. Just like-
<script>
var str = <?php echo $str; ?>;
var array = str.split(',');
</script>
OR, json_encode() can help you directly-
<script>
<?php
$js_array = json_encode($php_array);
echo "var js_array = ". $js_array . ";\n";
?>
</script>
Well you can do a for loop and echo the Javascript commands to fill the Javascript Array
<script>
var s4 = [[]];
<?php
$k_data = json_encode($k)
$i = 0;
foreach($k_data as $v) {
echo 's4.push([' , $i , ',Math.sin(' , $v , ')]);';
++$i;
}
?>
plot5.series[0].data = s4;
</script>
It seems that you are refering to a php variable in you javascript. Keep in mind that PHP is executed serverside, whereas javascript is executed by the browser. Therefore, you need to pass the PHP variable to your javascript. Assuming that your javascript and PHP are in one .php file, replacing above javascript with the following should work:
<?php $k_data_js = implode("','", $k_data); ?>
var k_data = <?php echo "['" . $k_data_js . "']"; ?>;
var s4 = [[]];
for(var i = 0; i<k_data.length; i++)
{
s4.push([i,k_data[i]]);
}
plot5.series[0].data = s4;
The variable is passed to javascript in the second line. From then on you can refer to k_data in your script.

Categories

Resources