0

I have a program where I generate a folder, its subfolders and files, and when I click the file, it has to show its content. My problem is that when I click, the function isn't called.

This is my function:

     function printFile(params) {
            //alert("Hello");
            $.ajax({
                    method: "GET",
                    url: "getFile.php",
                    data: {
                        q: params
                    }
                })
                .done(function(msg) {
                    $("#continut").html(msg);
                });

    }

    window.onload = function(){
        //alert("Hello");
        $("li").click(function() {

            printFile(this.id);
        });

    };

This is the body:

<?php
    function listAll($path, $test) {

        $fileList = glob($path);

        //Loop through the array that glob returned.
        foreach($fileList as $filename){
        $pieces = explode("/", $filename);
        if($test == 0){
        if (strpos(end($pieces), '.') !== false) {
        echo '<li class="file">'.end($pieces)."</li>", '<br>'; 
        }
        else
        echo '<ul class="folder">'.end($pieces).'</ul>', '<br>'; 
        }
        else
        {
        $spaceValue = 40*$test;
        echo '<ul class="spaceDiv" style="margin-left: '.$spaceValue.'px;">';
        if (strpos(end($pieces), '.') !== false) {
        echo '<li class="file" id="'.$filename.'" value="test">'.end($pieces)."</li>", '<br>'; 
        //echo $path;
        }
        else
        echo '<ul class="folder">'.end($pieces).'</ul>', '<br>'; 
        echo '</ul>';
        }
        listAll($path.end($pieces)."/*", $test+1);
        }
    }

    listAll("D:/xampp/htdocs/*", 0);



?>

And this is getFile.php:

<?php 

    $val = $_GET['q'];

    $fh = fopen($val,'r');
    while ($line = fgets($fh)) {
        echo($line."<br>");
    }
    fclose($fh);


?>

What can I do to call the function printFile on generated li?

Barrett
  • 23
  • 5

1 Answers1

2

You issue is that your click handler runs once on page load presumably before any li are in the document, you need to use .on to have a delegated handler.

$(document.body).on('click', 'li', function() {
   printFile(this.id);
});

I've made a working fiddle: https://jsfiddle.net/4we3ht67/2/

Here is the code from it:

HTML:

<div id="files"></div>

Javascript:

$(function() {
    function getFiles() {
    $("#files").html("<ul><li id=\"file-1\">File 1</li><li id=\"file-1\">File 2</li></ul>");
  }

  function printFile() {
    alert('File clicked!');
  }

  $(document).on('click', 'li', function() {
   printFile(this.id);
    });

  setTimeout(getFiles, 1000);
})
hidden_4003
  • 1,529
  • 1
  • 13
  • 19