user16165663
user16165663

Reputation:

jQuery .get Function Happening After page load (HAML)

So I'm using HAML and I'm looping through a set of URLs [url1, url2, url3] in order to pull an image from its page and put its src in another page. My code is as follows:

urls.each do |url|
   .img{:id => "url_#{url}"}
   :javascript
        var urlID = "#url_" + "#{url}";
        $.get('#{url}').then(function(res){
              var src = $(res).find('.image').attr('src');
              // console.log(urlID);
              $(`{urlID}`).attr('src', src);
            });

However, this doesn't seem to work as whenever I console.log(urlID) within the $.get function, it only will log the last url 3 times instead of url1 url2 url3, and I'm not really sure why? This means it replaces the same image src 3 times instead of displaying 3 separate images in each of the image classes. Does anyone know why?

Upvotes: 1

Views: 49

Answers (1)

charlietfl
charlietfl

Reputation: 171669

Wrap that in an IIFE to create a closure and prevent overwriting the variable before the request completes.

$.get() is asynchronous so as you create the same variable numerous times you overwrite the preceding version. When request completes it will be then using the very last value

(function(){
    // only scoped in this IIFE closure and
    // not affected by other versions in your loop
    let urlID = "#url_" + "#{url}";
    $.get('#{url}').then(function(res){
          var src = $(res).find('.image').attr('src');
          // console.log(urlID);
          $(`{urlID}`).attr('src', src);
     });

})();

Upvotes: 0

Related Questions