I have this situation where I have to check if a file exists on the server using JQuery. I can use Jquery Ajax to do this, but I need a listener which listens on the server for the presence of the file, and if it is there, then trigger some action. To provide more sense here is an example,
client--> checks on server for file(time 0)--> not present
client--> checks on server for file(time 5)--> not present
client--> checks on server for file(time 10)--> file present--> return some message to client.
So How do I implement a listener which checks for some particular file on the server and notifies the user when it is available.
You can use ajax polling..means check the server at a particular interval of time .
You can use setInterval function in java script to call a particular function ..And write ajax request in that function .and if the file found , just clear the timer
Check the sample code
var timerForLoadingResult= setInterval(checkServerForFile,4000);//call the fnction in every 4 seconds.write ajax in that function.
function checkServerForFile() {
$.ajax({
type: "POST",
cache: false,
url: url,
success: function (result) {
if(check result) //if the file is on server
{
//do something
clearInterval(timerForLoadingResult) // clear timer
}
; }
});
}
The ability to run different functions depending on the HTTP Status Code returned by the server was added in jQuery 1.5. So if the server responds with a 200 execute the function needed if file exists and if it returns a 404 execute the function required if it does not.
$.ajax({
statusCode: {
404: function() {
// file not found
},
200: function() {
// file found
}
}
});
For more info see: jQuery.ajax in the jQuery docs.
Edit: From your comments I can see that you need to keep checking until the file exists. If so just wrap the request in a function and then call that function if the file is not found. Use setTimeOut though else you will be spamming the server with connection requests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With