0

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);
  • 2
    Move the alerts into the done/fail - then go read about asynchronous vs synchronous – rlemon Aug 09 '13 at 13:36
  • Let me stackoverflow it for you: http://stackoverflow.com/questions/3646914/how-do-i-check-if-file-exists-in-jquery-or-javascript – viarnes Aug 09 '13 at 13:38
  • @Servani: exaclty in that thread i found some posts below (http://stackoverflow.com/a/14691735/2179639) that the .get method should be used. was that wrong? – Steffen Eppler Aug 09 '13 at 13:50

2 Answers2

0

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);
    });
Lapixel
  • 144
  • 6
0

The alert sentences occur before the get call returns. The functions specified for .done and .fail with be invoke once the response comes back. As of now, the $.get() goes to the server and right after that the alert() sentences gets executed before the response is back. Try:

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