0

I am trying to find out whether or not a file exists, before trying to download it. The file is a ClickOnce application.

I have already tried the following code, but this does not work (maybe because the URL is on a different server and domain?);

$.ajax({
    url: 'http://www.example.com/somefile.ext',
    type: 'HEAD',
    error: function()
    {
        //File does not exist
    },
    success: function()
    {
        // File exists
    }
});

Is there another solution, or is there a means to get this one to work?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mystogan
  • 547
  • 4
  • 21

3 Answers3

0

Yes, this should not work if the URL is on a different server. If you want to make this work, you will need control over the server where the URL is downloaded from. If so, you should set the Access-Control-Allow-Origin header to the name of the server from which your JavaScript is loaded.

See Stack Overflow question jQuery AJAX cross domain for more details.

Community
  • 1
  • 1
Hans Then
  • 10,935
  • 3
  • 32
  • 51
0

You cannot make Cross-Domain Calls this easily (CORS). It is better and safer to call a script on your server which checks for the existence of the file and returns an according result.

Christoph
  • 50,121
  • 21
  • 99
  • 128
  • @drbaltar I don't understand you... How do you want to do your ajax request in the first place if you don't know the servername? – Christoph Sep 17 '12 at 15:09
0

Besides what the others have said, you should also check the errorThrown argument to the error function to be "Not Found". Otherwise you may be assuming a file doesn't exist when really a different error occurred.

When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error."

Samuel
  • 16,923
  • 6
  • 62
  • 75