mardi 21 juin 2016

HTML onclick function doesn't call through PHP echo

Originally I had the following to produce a menu using PHP:

<ul>
   <?php 
         $items = mysqli_query($con, "SELECT DISTINCT item FROM table");
         while ($row = mysqli_fetch_array($items)) { ?>
             <li><a href='#' onclick='myFunction(<?php echo $row['item'] ?>)'><?php echo $row['item'] ?></a></li><? php 
         } ?>
</ul>

I had this code inside an index.php page surrounded by html. The is to produce a menu from items in a database. In this form it worked fine and called 'myFunction(string)' which is in a seperate global.js file.

function myFunction(string) {
$('#container').load('php/getContent.php', {string: string});
}

getContent.php is similar to the php above. except it uses a where clause in the query which it extracts from the string.


So my problem arose when I went to clean up the code which produces the menu. I added the following function to global.js

$(document).ready(function() {
    $('#menu').load('php/getMenu.php');
});

getMenu.php looks like this:

$items = mysqli_query($con, "SELECT DISTINCT item FROM table");

echo "<ul class='tab'>";
while ($row = mysqli_fetch_array($items) {
    echo "<li><a href='#' onclick='myFunction(".$row['item'].")'>".$row['item']."</a></li>";
}
echo "</ul>"

This works correctly in producing the menu items as before except the onclick function no longer works. Placing an anonymous inline onclick function did work however so I figured it may be the $(document.ready() inside the global.js file causing issues. I moved the $(document).ready() back into index.php in a script tag to check, still not working.

I originally had the script tags as the last elements in the body so I moved them up into the header to check if that changed anything but that also didn't work.

the header tag looks as follows:

<script src='scripts/jquery-3.0.0.js'></script>
<script src='scripts/global.js'></script>
<script>
     $(document).ready(function() {
         $('#menu').load('php/getMenu.php');
     });
</script>

all my php files are in a subfolder called php and all my js files in a subfolder called scripts.


So firslty, does it matter if I have the $(document).ready() in a js file with other functions, does that mess with the other functions?

Secondly any idea on why the function is no longer being called?

Thanks in Advance.

Aucun commentaire:

Enregistrer un commentaire