PogoMips
PogoMips

Reputation: 3757

check if file exists, display according message, jQuery

I need a global function that checks if a file exists. I need to reuse that function for several methods so I just want it to return true or false. I tried to make it asynchronous but I can't get it to work. This is the function:

  function checkIndex(){
      $.ajax({
          url:'upload/_3.fdt',
          type:'HEAD',
          async: false,
          error: function(){
                return false;   
          },
          success: function(){
                return true;
          }
      });
}

this is one the functions that calls the checkIndex()

$(function(){
    $(document).ready( function(){

        if(checkIndex() == false)
            $('#check').html('<td><img src="img/cross.gif" /></td><td>No index present</td>');
        else
            $('#check').html('<td><img src="img/check.gif" /></td><td>Index is present</td>');

    });
   });

How can I make this work?

Upvotes: 2

Views: 4094

Answers (2)

adeneo
adeneo

Reputation: 318182

I'd return the deferred object from the ajax function, and just insert the html based on wether or not the ajax function failed or not :

function checkIndex(file){
    return $.ajax({
        url : file,
        type:'HEAD'
    });
}

$(function(){
    checkIndex('upload/_3.fdt').done(function() {
        $('#check').html('<td><img src="img/check.gif" /></td><td>Index is present</td>');
    }).fail(function() {
        $('#check').html('<td><img src="img/cross.gif" /></td><td>No index present</td>');     
    });
});

If you pass the filename to check to the function, it's very reusable as well.

Upvotes: 3

jbabey
jbabey

Reputation: 46647

In general, if you find yourself using async: false, you're doing it wrong.

You can solve this problem by taking advantage of the fact that $.ajax returns a Deferred object which you can interact with like so:

function checkIndex(){
    return $.ajax({
        url:'upload/_3.fdt',
        type:'HEAD'
    });
}

checkIndex().done(function () {
    $('#check').html('<td><img src="img/check.gif" /></td><td>Index is present</td>');
}).fail(function () {
    $('#check').html('<td><img src="img/cross.gif" /></td><td>No index present</td>');
});

For more information, see the documentation on jQuery Deferred Objects.

Upvotes: 0

Related Questions