1

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); 
trincot
  • 317,000
  • 35
  • 244
  • 286
schenker
  • 941
  • 3
  • 12
  • 25

2 Answers2

1

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!

NewToJS
  • 2,762
  • 3
  • 14
  • 22
  • Method 1 looks promising, let me see if it works. Thanks so much for your help. – schenker Mar 09 '17 at 11:16
  • 1
    @schenker Very welcome. If you have any problems with this, just let me know and I will see if I can be of any further assistance. – NewToJS Mar 09 '17 at 12:19
0

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>

';
?>
Dev Man
  • 2,114
  • 3
  • 23
  • 38