How do I check if a file on my server exists in jQuery or pure JavaScript?
Advertisement
Answer
With jQuery:
JavaScript
x
13
13
1
$.ajax({
2
url:'http://www.example.com/somefile.ext',
3
type:'HEAD',
4
error: function()
5
{
6
//file not exists
7
},
8
success: function()
9
{
10
//file exists
11
}
12
});
13
EDIT:
Here is the code for checking 404 status, without using jQuery
JavaScript
1
8
1
function UrlExists(url)
2
{
3
var http = new XMLHttpRequest();
4
http.open('HEAD', url, false);
5
http.send();
6
return http.status!=404;
7
}
8
Small changes and it could check for status HTTP status code 200 (success), instead.
EDIT 2: Since sync XMLHttpRequest is deprecated, you can add a utility method like this to do it async:
JavaScript
1
10
10
1
function executeIfFileExist(src, callback) {
2
var xhr = new XMLHttpRequest()
3
xhr.onreadystatechange = function() {
4
if (this.readyState === this.DONE) {
5
callback()
6
}
7
}
8
xhr.open('HEAD', src)
9
}
10