Javascript/jquery check if file exists and display it

Section on my website with a list of fixtures.
When I click on one it loads the fixture information in a modal window - each club might have an image so I want to check if there is an image and if so display it otherwise display a generic image.
Code is below:
$('#fixModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget) // Button that triggered the modal

  var hclub = button.data('hclubid')


  imgpath = "/images/clubcrests/"
  homecrest = imgpath + hclub + '.jpg'
  gencrest = imgpath + 'generic.jpg'


$.get(homecrest)
    .done(function() { 
        homecrestsrc = "<img src='" + homecrest + "'>"

    }).fail(function() { 
       homecrestsrc = "<img src='" + gencrest + "'>"
    })

  var modal = $(this)


  modal.find('.fixmodhomec').html(homecrestsrc)


})

Open in new window



But first time I click on it I get the error - homecrestsrc is not defined - the $.get seems to run after the modal.find.
If I click on it again it displays but always the image it should have from the previous time the button was clicked.
How can I make sure the $.get bit runs first?
LVL 3
harris9999Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Alexandre SimõesManager / Technology SpecialistCommented:
You can do something like:
$('#fixModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget) // Button that triggered the modal

  var hclub = button.data('hclubid');

  imgpath = "/images/clubcrests/";
  homecrest = imgpath + hclub + '.jpg';
  gencrest = imgpath + 'generic.jpg';

$.get(homecrest)
    .done(function() { 
        homecrestsrc = "<img src='" + homecrest + "'>";
    }).fail(function() { 
       homecrestsrc = "<img src='" + gencrest + "'>";
    }).always(function(){
       var modal = $(this);
       modal.find('.fixmodhomec').html(homecrestsrc);
    });

})

Open in new window

Word of advise:
- don't forget ; at the end of the lines
- ba careful about declaring variables without the var before (I hope imgpath, homecrest and gencrest variables are being declared somewhere else before this code)

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Bernard S.CTOCommented:
also be careful that your js function is called after you have loaded the rest of the page.
place it just before </body> or the the list of functions launched by onload()
Steve BinkCommented:
Just a brief expansion of Alexandre's answer.

The important point here is the jQuery's AJAX calls run asynchronously by default.  That means they send the request, and allow the rest of javascript to keep running while awaiting the response.  When the response returns, it is fielded by a handler, not the original sequence of code generating the request.

If you want to make sure something happens after an AJAX response has been received, you need to use the AJAX handlers to specify the timing/conditions under which the extra code runs.  Read through a bit at http://api.jquery.com/jquery.ajax/#jqXHR to better understand how the handlers work.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.