Nicholas Hazen
Nicholas Hazen

Reputation: 1315

Uploading and processing a file with PHP and Ajax

I would like to build a site that allows me to upload a file, and then show the progress of processing the file live. The client would upload a delimited file. Once uploaded I would verify the headers / columns in the data. If this follows a given template then I would process the lines one at a time and would like to give live feed back to the user as this happens. I know PHP is ran at the time of the get request and thus I figure the approach would require ajax to accomplish my goals. How do I go about doing something like this. Any pseudo code, examples, or tutorials would be greatly appreciated.

Upvotes: 1

Views: 1276

Answers (1)

Josh Mein
Josh Mein

Reputation: 28625

I have done something similar in the past. What you need to do it start the file processing. After a set interval of time, such as a second, you can use an ajax call to poll the server to see the progress of processing the file.

By the way, I would recommend jqueryUI progressbar for the progress bar and uploadify for the uploader.

Javascript:

setTimeout("UpdateProgressBar();", 1000);

$.ajax({
    type: "POST",
    async: true,
    data: // params go here
    url: // path to web method
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
         // Do stuff when file is finished processing
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        if (errorThrown != null)
            alert(textStatus + " : " + errorThrown);
    }
});

function UpdateProgressBar() {
    $.ajax({
        type: "POST",
        async: true,
        data: // my params go here
        url: // path to web method
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            var totalRecords = result.d.TotalRecords;
            var recordsProcessed = result.d.RecordsProcessed;
            var percentProcessed = pagesProcessed / totalRecords;

            $('#div_ProgressBar').progressbar("value", percentProcessed);

            if (recordsProcessed < totalRecords)
                setTimeout("UpdateProgressBar();", 800);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (errorThrown != null)
                alert(textStatus + " : " + errorThrown);
        }
    });

Upvotes: 1

Related Questions