Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to use PHP and jQuery to display files in a directory.

I have incorporated Datatables to list all records in a database. Some of these records have files linked to them. The user would click a link which opens a modal window which should then display all the files in that record's directory.

Starting with the PHP

<?php
if(isset($_POST['editpartnercode']))
{
    $partnerCode = $_POST['editpartnercode'];

    $dir = "D:/CargoDocsPDFs/" . $partnerCode;

    $ffs = scandir($dir);

    foreach($ffs as $ff)
    {               
        if($ff != '.' && $ff != '..')
        {   
            echo $ff;
            // echo json_encode($out); // <-this didn't work either
        }
    }       
}
?>

Here is the jQuery that uses $.post to pass the editpartnercode variable:

$.post('process/displayFiles.php', {editpartnercode:editpartnercode}, function(data)
{
    console.log(data);
    var obj = JSON.parse(data);
    $('#allFiles').empty();
    var htmlToInsert = obj.map(function (item)
    {
        return '<li><b>' + item.ff + '</b></li>';
    }).join('');
    $('#allFiles').html(htmlToInsert);      
});

The HTML looks like this:

<div class="row">
    <div class="col-lg-12">
        <p>Uploaded Files</p>
        <ul id="allFiles">
        </ul>
    </div>
</div>

I can see the file names in the console, but I am also getting this error:

VM2087:1 Uncaught SyntaxError: Unexpected token T in JSON at position 0
at JSON.parse (<anonymous>)
at Object.success (genhome.js:210)
at u (jquery.js:2)
at Object.fireWith [as resolveWith] (jquery.js:2)
at k (jquery.js:2)
at XMLHttpRequest.<anonymous> (jquery.js:2)

To reiterate, all I am trying to do is list the files associated with the editpartnercode (which is the directory name).

What am I missing that will get rid of that error and print the files on the screen?

Edit

Here is how the files are being printed in the console:

TEST1234567.TIFFTEST1234567_121218_100637.TIFFThumbs.db
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
198 views
Welcome To Ask or Share your Answers For Others

1 Answer

When trying to return json array from pure php script you could also set the header of the response

header('Content-type: application/json');
echo json_encode($ff);

But I would also populate the array first and return whole result in the end.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...