This question has already been asked here and here. But I have tried three of the answers with no good luck. I am using a system called Niagara which is acting as a web server, which may be the reason these techniques did not work. Nonetheless, I feel there must be a way to check for the existence of a file, not the existence of a 404 or 200 or 0.
Asked
Active
Viewed 5.2k times
3
-
What do want to check where for a file? Is the browser checking the user's local system? Is the webserver checking for a file on a remote host? Is the browser checking for the file on the server? Some other combination? – Alex Wayne May 14 '13 at 21:32
-
@AlexWayne The users browser would check for a file on the internet. – dezman May 14 '13 at 21:33
-
On your own webserver or someone elses? Is `mydomain.com/mypage.html` checking on a file somewhere like `somewhereelse.com/somefile.txt`? Or is `mydomain.com/mypage.html` check on a file somewhere like `mydomain.com/somefile.txt`? – Alex Wayne May 14 '13 at 21:36
-
@AlexWayne I would like the answer to work for both circumstances, if possible, but currently I will be looking on the same domain that is checking. – dezman May 14 '13 at 21:38
-
1If it's on the same domain, @karthikr has the answer. But on other domains it's not that simple due to the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy). Which means you cannot achieve this without their server letting you, or proxying the request through your own server, both of which are a bit more complicated. – Alex Wayne May 14 '13 at 21:41
-
1Also it's worth noting that "existence of a file" is a bit vague. Yes, many web servers serve "files" directly from the file system. But ultimately most of the time it is an HTTP request and an HTTP response. – Aaron Gibralter May 14 '13 at 21:45
1 Answers
13
You can use $.ajax
$.ajax({
url: 'example.com/abc.html', //or your url
success: function(data){
alert('exists');
},
error: function(data){
alert('does not exist');
},
})

karthikr
- 97,368
- 26
- 197
- 188
-
will this work with relative paths, lets say i just have url: 'abc.html'? – dezman May 14 '13 at 21:31
-
4That answer was given on one of the referenced questions. Why is this different? – Diodeus - James MacFarlane May 14 '13 at 21:32
-
-
Refer to this: http://stackoverflow.com/questions/3646914/how-do-i-check-if-file-exists-in-jquery-or-javascript?answertab=oldest#tab-top This answer is essentially the same – karthikr May 14 '13 at 21:37
-
-
1