views:

81

answers:

2

I just want to use javescript /jquery to determine if and xml file exsists

I don't need to process it I just need to know that its available or not.

can seem to find simple check.

thanks

Edit trying load here is my code

 jQuery.noConflict();

  jQuery(document).ready(function(){
var photo = '223';
var exists = false;

jQuery.load('/'+photo+'.xml', function (response, status, req) { 
    if (status == "success") { 
        exists = true;
    }
});
   });
A: 

Your question isn't clear to me. If I understand, you want to verify whether a file (the XML) is present or not in the HTTP server.

That's correct? If so, you can just do:

$.get('url-to-file.xml', function(response, status, req) {
    if (status == 'success') {
        alert('exists');
    }
});

EDITED: As pointed by @lzyy on comments, .get() only calls the callback upon success. However, I'd stick to the .load() using $(document) as selector. See:

$(document).load('url-to-file.xml', function(response, status, req) {
    if (status == 'success') {
        alert('exists');
    } else if (status == 'error') {
        alert('doesnt exist');
    }
});
jweyrich
currently I'm getting jQuery.load is not a function
mcgrailm
Sorry, I meant $.get(). Fixed the snippet.
jweyrich
$.get()'s callback function will be executed only if the response has a successful response code
lzyy
@lzyy indeed. Thanks for the note! I used .load() at first because it works the way he expected, but then I figured out it can't be used without a selector. However, I'd suggest him to use $(document) as selector.
jweyrich
+3  A: 

Assuming you are talking about an xml file on the server, you could do a ajax request and then write a custom error handler to check the error response message. You'll need to know what the exact error message code is for a missing file (usually 404). You can use Firebug Console to check what the exact error message and code is.

$.ajax({
     type: "GET",
     url: "text.xml",
     dataType: "xml",
     success: function(xml) {
        alert("great success");
     }, 
     error: function(xhr, status, error) {
        if(xhr.status == 404)
        {
            alert("xml file not found");
        } else {
            //some other error occured, statusText will give you the error message
            alert("error: " + xhr.statusText);
        }
     } //end error
 }); //close $.ajax(
Erikk Ross
that works thanks
mcgrailm
This is a good answer, but it seems like it would make more sense to check `xhr.status === 404`, rather than `xhr.statusText == "Not Found"`, as status will contain a numerical error code rather than arbitrary string which may or may not even be set by the server's error handler depending on the implementer. If you really wanted to be robust you could check `if(xhr.status >== 400) { alert('failed'); }`.
Nathan Taylor
@Nathan Taylor excellent suggestion, I've updated my answer.
Erikk Ross