Checking if a file(url) exists using Javascript (AJAX)

suhaib

New Member
Messages
8
Reaction score
0
Points
0
:cool: Using javascript to check whether a file(url) exists.

If you want to check whether a Web resource exists before trying to download it, then you didn't
want to download the whole thing just to check whether it’s there. You can use HEAD requests to check whether it exists, and use up a lot less bandwidth doing so.

Code:
[COLOR=Black]http_check = getHTTPObject();

function getHTTPObject(){[/COLOR] 
  //Create a boolean variable to check for a valid Internet Explorer instance.
[COLOR=Black]var xmlhttp = false;[/COLOR]
//Check if we are using IE.
 [COLOR=Black]try {[/COLOR]
  //If the Javascript version is greater than 5.
  [COLOR=Black]xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {[/COLOR]
  //If not, then use the older active x object.
  [COLOR=Black]try {[/COLOR]
  //If we are using Internet Explorer.
  [COLOR=Black]xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 } catch (E) {[/COLOR]
//Else we must be using a non-IE browser.
[COLOR=Black]xmlhttp = false;[/COLOR]
 [COLOR=Black]}
}[/COLOR]
//If we are using a non-IE browser, create a javascript instance of the object.
[COLOR=Black] if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
 xmlhttp = new XMLHttpRequest();
 }
 
  return xmlhttp;
}


function check_file(path_of_file) 
{
    http_check.open("HEAD", path_of_file);
    http_check.onreadystatechange = handleHttpResponse_check;
    http_check.send(null);

    function handleHttpResponse_check()
    {
        if(http_check.readyState == 4){
            if (http_check.status == 200) {
                [B]keepgoing();[/B]
            }else if (http_check.status == 404) {
                [B]callanotherfunction();[/B]
            }
        }
    }
}[/COLOR]


Usage:



  1. Save the above code as file_check.js.
  2. Link the script to the page by entering the following code between the <head> </head> tags.
    HTML:
    <script language="javascript" src="file_check.js" type="text/javascript"></script>
  3. Then use it calling function check_file(path).
    Example:
    HTML:
    <a href="javascript:" onclick="check_file('sample.php')">CHECK</a>
  4. The result you can set in javascript 'file_check.js' by defining two functions "keepgoing()" and "callanotherfunction()" which i used in the above script.
Hopes that it will be useful to you.
T h a n k s . . .
 
Top