schenker
schenker

Reputation: 953

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

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); 

Upvotes: 1

Views: 433

Answers (2)

NewToJS
NewToJS

Reputation: 2772

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!

Upvotes: 1

Dev Man
Dev Man

Reputation: 2137

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>

';
?>

Upvotes: 0

Related Questions