简体   繁体   中英

Upload PHP file into HTML table using Ajax

I am very new to HTML/javascript and I have seen a bunch of questions like this but I can't seem to make head of tail of the solution provided. I have the following HTML code in the body section(including what is relevant):

<div>
    <ul id="playerNames">
        <li><b>Harden</b></li>
        <li><b>Giannis</b></li>
        <li><b>Lebron</b></li>
        <li><b>Booker</b></li>
        <li><b>Lavine</b></li>
        <li><b>Westbrook</b></li>
        <li><b>Jokic</b></li>
    </ul>
</div>

There is some javascript below (also in the body of the same file):

<script type = "text/javascript">
    $(document).ready(function(){
        $( "playerNames" ).load( 'nba2019_names.php' );
    });
</script>

And I have the following php code in a separate file that it meant to load a csv file that I am downloaded. All of these files are in the same folder.

$h=fopen('2019_nba_player_names.csv','r');

$data = fgetcsv($h, 1000, ",");

while(($data = fgetcsv($h, 1000, ",")) !== FALSE){
    echo $row."\n";
}

What I am trying to do is get the information in the csv to become an html list, and then replace the html code/list that is already in the ul. The names in the current ul are just placeholders. However, all that loads into the page is the placeholder names, and the code to get the csv has no effect. Can anybody help me out with this?

Try: ajax code

$.ajax({
      method: GET
      url:"nba2019_names.php",
      success:function(res){
     $("#playerNames").html(res)
      }
    })

php code

$h=fopen('2019_nba_player_names.csv','r');

$data = fgetcsv($h, 1000, ",");

while(($data = fgetcsv($h, 1000, ",")) !== FALSE){
    echo "<li>$row</li>"."\n";
}

update : you can use this code to get data from csv file

$row = 1;
if (($handle = fopen("2019_nba_player_names", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo "<li>$data[$c]</li>";
        }
    }
    fclose($handle);
}

reference

Why have JS at all? I'll assume for now that there is only a bunch of names in your.csv file.

<div>
  <ul id="playerNames">
  <?
    $h=fopen('2019_nba_player_names.csv','r');
    while(($data = fgetcsv($h, 1000, ",")) !== FALSE){
      echo "<li>" . $data[0] . "</li>\n";
    }
  ?>
  </ul>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM