SecureLive
SecureLive

Reputation: 80

jQuery .load inside .each

tried to search for this, although I am not even sure what I am searching for. My problem is this:

$.getJSON('process.countfiles.php?action=getfiles', function(data) {
    $.each(data, function(name, value){
        $("#displayfile").load("process.files.php?file="+value, function(){
        });
    });
});

OK, I am having a script (process.countfiles.php) with 2 functions, 1 - count the files and build a file list in a .dat file. Then number 2 is open the .dat file and process the files individually.

The first parts works great, so let move to the second part... I have the data being passed from PHP like this:

PHP Code:

$fh = fopen($dirdatafn, "r"); 
    while (!feof($fh)){ 
        $data_file_line[] .= fgets($fh); 
    } 
    @fclose ($fh); 
    echo json_encode($data_file_line); 

Now back to the JS (jQuery is the framework I am using for this) data is the array of $data_file_line from the PHP, it gets the data with no problem, then it should start separating them with the .each

The problem is, it will try loading all 7,000+ at the same time and send them all to the process.files.php, when I would like it to handle one at a time.

Any help would be appreciated.

Thank you, Jeff

Upvotes: 2

Views: 1088

Answers (2)

Michal
Michal

Reputation: 13649

Providing you JSON returns an array you can do this (i have not tested it). Basically to process each file indiviudally you need to wait till the success callback fires before your next file is processed:

    var data_arr;
    $(function() {
        $.getJSON('process.countfiles.php?action=getfiles', function(data) {
            data_arr = data;
            requestFiles(data_arr[0])
        });
        function requestFiles(i) {

            $("#displayfile").load("process.files.php?file=" + data_arr[i], function() {
                if(i < data_arr.length) {
                    requestFiles(i + 1);
                }
            });
        }

    })

Upvotes: 1

John W
John W

Reputation: 1522

You can tell jQuery to make your calls to "process.files.php?file=" synchronously if you use the more general $.ajax() method instead of $("selector").load();

replace

$("#displayfile").load("process.files.php?file="+value, function(){
        });

with

$.ajax("process.files.php?file="+value, {
        async: false, // this is true by default
        success: function(data) {
            $("#displayfile").html(data); // this is what you were doing by calling $.load
            // do other stuff
        }
     });

Upvotes: 1

Related Questions