Search code examples
javascriptjquerygetdelay

check for file with jquery and work with the result


I want to check if a image with a certain extension exists, if so, i want to alert the extension otherwise "unknown". The detection part of the code works fine, but when I alert the imagevar the first time, the var is empty, when I add another alert the var has the correct value.

Does it take to long for the $.get command to complete or where does the delay come from?

var extension = 'jpg';
var url = 'someimagefile.' + extension;
var imagevar = '';

$.get(url)
  .done(function() {
   imagevar = extension; 
    })
  .fail(function() {
    imagevar = 'unknown'; 
    });

alert(imagevar);
alert(imagevar);

Solution

  • You need to use the alert in the callback after assigning a value to imagevar, otherwise your alert command will most likely fire before your $.get is done and thus imagevar assigned a value.

    So make sure to put any code that needs the result of the $.get in the callback.

    var extension = 'jpg';
    var url = 'someimagefile.' + extension;
    var imagevar = '';
    
    $.get(url)
      .done(function() {
       imagevar = extension; 
       alert(imagevar);
        })
      .fail(function() {
        imagevar = 'unknown'; 
        alert(imagevar);
        });