views:

256

answers:

3

Hi,

How can I check an existence of a file (It is an xml file that I would like to check in this case) with JavaScript?

Thanks, Burak Ozdogan

+2  A: 

If the file is located on the same host that served the page containing the javascript you could try sending an ajax request and verify the returned status code:

function checkFile(fileUrl) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }

    self.xmlHttpReq.open('HEAD', fileUrl, true);
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            if (self.xmlHttpReq.status == 200) {
                alert('the file exists');
            } else if (self.xmlHttpReq.status == 404) {
                alert('the file does not exist');
            }
        }
    }
    self.xmlHttpReq.send();
}

checkFile('/somefile.xml');
Darin Dimitrov
+1 for using a HEAD request
I.devries
+1  A: 

Javascript doesn't really have any file handling functions. Your best bet is to do the check server side and send some context back to the client.

If you want to get super hacky you COULD call an xmlHttpRequest (If you're using jQuery take a look at the $.ajax function)

Once you call $.ajax you can use the success/error handlers to determine what to do. It should spit out an error if the file doesn't exist.

This of course is NOT a recommended way to do this.

Bartek
+1  A: 

if you're using jQuery, you can try to load the file

$.ajax({
  type: "GET",
  url: "/some.xml",
  success: function()
  { /** found! **/},
  error: function(xhr, status, error) {
    if(xhr.status==404)
      { /** not found! **/}
  }
});

if you're not using jQuery:

function ajaxRequest(){
 var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] 
 //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
 if (window.ActiveXObject){ 
  for (var i=0; i<activexmodes.length; i++){
   try{
    return new ActiveXObject(activexmodes[i])
   }
   catch(e){
    //suppress error
   }
  }
 }
 else if (window.XMLHttpRequest) // if Mozilla, Safari etc
  return new XMLHttpRequest()
 else
  return false
}

var myrequest=new ajaxRequest()
myrequest.onreadystatechange=function(){
 if (myrequest.readyState==4){ //if request has completed
  if (myrequest.status==200 || window.location.href.indexOf("http")==-1){ 
    // FOUND!
  }
 }
}

myrequest.open('GET', 'http://blabla.com/somefile.xml', true);
Anwar Chandra
the "#somehiddenplace" is not really needed with jquery, you can just use $.get, $.post or $.Ajax without unneeded markup
I.devries
@vatos you're right. thanks
Anwar Chandra
It is updated. better to use $.ajax
Anwar Chandra