2

I want to check for a file with jQuery/Ajax.

I'm generating a file and this can take 30 - 90 seconds.

I want jQuery/Ajax to check every X (e.g. 5) seconds, if the file already exists (has been generated).

How can I do this?

Additionally I want to know if the file has really been generated completly and so I want to check for unique access (or if an error occurs, because the document is getting written).

Is this possible?

I've found the following code snippet to check for files, but it seems to always send an "OK".

$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error:
    function(){
        //do something depressing
    },
success:
    function(){
        //do something cheerful :)
    }
});

source: http://www.ambitionlab.com/how-to-check-if-a-file-exists-using-jquery-2010-01-06

Keith L.
  • 2,084
  • 11
  • 41
  • 64
  • You want to [repeat your function every x seconds](http://stackoverflow.com/questions/3138756/jquery-repeat-function-every-60-seconds), right? – sp00m May 14 '12 at 09:27

3 Answers3

2

How are you generating your file?

IMO, what's happening is that at the beginning of file generation, your http://www.example.com/somefile.ext already exists on the server, while its content is being generated. That's why you get the success status all the times.

A better approach would be to create a server hook (e.g. http://www.example.com/checkFileStatus) that would return {generated: true, fileUrl: 'yourFile'} and use setTimeout to check on that instead.

Thach Mai
  • 915
  • 1
  • 6
  • 16
1
success:
    function(res){
        // res -> will catch the response from server if file has been generated
        // suppose server will send 'ok' after file generation so, res == 'ok'
        // now check for response in every 5 seconds
        var tm = setInterval(function() {
                     if(res == 'ok') {
                        alert('File made');
                        clearInterval(tm);

                        // now here do what you want

                     }
                 }, 5000);
    }
The System Restart
  • 2,873
  • 19
  • 28
0

you may use this instead of $.ajax

$('#divid').load('url').fadeIn("slow");}, 10000); // refresh every 10000 milliseconds

And add your php/ SQL code in the file "url"

John
  • 163
  • 1
  • 11