1

I am trying to fetch the img src which is in flip class. Below is the HTML that I am having. I basically want to get the src img and change it on the click on swatch-option.

<li class="item product product-item">
   <div class="product-item-info" data-container="product-grid">
      <a href="http://127.0.0.1/magento2252/stellar-solar-jacket.html" class="product photo product-item-photo" tabindex="-1">
      <span class="product-image-container" style="width:240px;">
      <span class="product-image-wrapper" style="padding-bottom: 125%;">
      <img class="product-image-photo" src="http://127.0.0.1/magento2252/pub/media/catalog/product\cache\c687aa7517cf01e65c009f6943c2b1e9\/w/j/wj01-blue_main.jpg" width="240" height="300" alt="Stellar Solar Jacket" style="display: block;">
      <img class="flip" src="http://127.0.0.1/magento2252/pub/media/catalog/product//w/j/wj01-red_back.jpg" width="240" height="300" alt="Stellar Solar Jacket" style="display: none;">    
      </span>
      </span>
      </a>
      <div class="product details product-item-details">
         <strong class="product name product-item-name">
         <a class="product-item-link" href="http://127.0.0.1/magento2252/stellar-solar-jacket.html">
         Stellar Solar Jacket                            </a>
         </strong>
         <div class="product-reviews-summary short">
            <div class="rating-summary">
               <span class="label"><span>Rating:</span></span>
               <div class="rating-result" title="67%">
                  <span style="width:67%"><span>67%</span></span>
               </div>
            </div>
            <div class="reviews-actions">
               <a class="action view" href="http://127.0.0.1/magento2252/stellar-solar-jacket.html#reviews">3&nbsp;<span>Reviews</span></a>
            </div>
         </div>
         <div class="price-box price-final_price" data-role="priceBox" data-product-id="1225" data-price-box="product-id-1225">
            <span class="normal-price">
            <span class="price-container price-final_price tax weee">
            <span class="price-label" style="display: inline;">As low as</span>
            <span id="product-price-1225" data-price-amount="75" data-price-type="finalPrice" class="price-wrapper "><span class="price">$75.00</span></span>
            </span>
            </span>
         </div>
         <div class="swatch-opt-1225" data-role="swatch-option-1225">
            <div class="swatch-attribute size" attribute-code="size" attribute-id="141">
               <div aria-activedescendant="" tabindex="0" aria-invalid="false" aria-required="true" role="listbox" aria-label="Size" class="swatch-attribute-options clearfix">
                  <div class="swatch-option text" id="option-label-size-141-item-168" aria-checked="false" aria-describedby="option-label-size-141" tabindex="0" option-type="0" option-id="168" option-label="S" aria-label="S" option-tooltip-thumb="" option-tooltip-value="S" rel="1218" role="option">S</div>
                  <div class="swatch-option text" id="option-label-size-141-item-169" aria-checked="false" aria-describedby="option-label-size-141" tabindex="0" option-type="0" option-id="169" option-label="M" aria-label="M" option-tooltip-thumb="" option-tooltip-value="M" rel="1221" role="option">M</div>
                  <div class="swatch-option text" id="option-label-size-141-item-170" aria-checked="false" aria-describedby="option-label-size-141" tabindex="0" option-type="0" option-id="170" option-label="L" aria-label="L" option-tooltip-thumb="" option-tooltip-value="L" rel="1224" role="option">L</div>
               </div>
            </div>
            <div class="swatch-attribute color" attribute-code="color" attribute-id="93" option-selected="50">
               <div aria-activedescendant="option-label-color-93-item-50" tabindex="0" aria-invalid="false" aria-required="true" role="listbox" aria-label="Color" class="swatch-attribute-options clearfix">
                  <div class="swatch-option color selected" id="option-label-color-93-item-50" aria-checked="false" aria-describedby="option-label-color-93" tabindex="0" option-type="1" option-id="50" option-label="Blue" aria-label="Blue" option-tooltip-thumb="" option-tooltip-value="#1857f7" rel="1222" role="option" style="background: #1857f7 no-repeat center; background-size: initial;"></div>
                  <div class="swatch-option color" id="option-label-color-93-item-58" aria-checked="false" aria-describedby="option-label-color-93" tabindex="0" option-type="1" option-id="58" option-label="Red" aria-label="Red" option-tooltip-thumb="" option-tooltip-value="#ff0000" rel="1223" role="option" style="background: #ff0000 no-repeat center; background-size: initial;"></div>
                  <div class="swatch-option color" id="option-label-color-93-item-60" aria-checked="false" aria-describedby="option-label-color-93" tabindex="0" option-type="1" option-id="60" option-label="Yellow" aria-label="Yellow" option-tooltip-thumb="" option-tooltip-value="#ffd500" rel="1224" role="option" style="background: #ffd500 no-repeat center; background-size: initial;"></div>
               </div>
            </div>
         </div>
         <div class="product-item-inner">
            <div class="product actions product-item-actions">
               <div class="actions-primary">
                  <form data-role="tocart-form" data-product-sku="WJ01" action="http://127.0.0.1/magento2252/checkout/cart/add/uenc/aHR0cDovLzEyNy4wLjAuMS9tYWdlbnRvMjI1Mi93b21lbi90b3BzLXdvbWVuL2phY2tldHMtd29tZW4uaHRtbA%2C%2C/product/1225/" method="post">
                     <input type="hidden" name="product" value="1225">
                     <input type="hidden" name="uenc" value="aHR0cDovLzEyNy4wLjAuMS9tYWdlbnRvMjI1Mi9jaGVja291dC9jYXJ0L2FkZC91ZW5jL2FIUjBjRG92THpFeU55NHdMakF1TVM5dFlXZGxiblJ2TWpJMU1pOTNiMjFsYmk5MGIzQnpMWGR2YldWdUwycGhZMnRsZEhNdGQyOXRaVzR1YUhSdGJBJTJDJTJDL3Byb2R1Y3QvMTIyNS8,">
                     <input name="form_key" type="hidden" value="OIKwIjHelyF4WqGg">                                            <button type="submit" title="Add to Cart" class="action tocart primary">
                     <span>Add to Cart</span>
                     </button>
                     <input class="swatch-input super-attribute-select" name="super_attribute[141]" type="text" value="" data-selector="super_attribute[141]" data-validate="{required: true}" aria-required="true" aria-invalid="false"><input class="swatch-input super-attribute-select" name="super_attribute[93]" type="text" value="" data-selector="super_attribute[93]" data-validate="{required: true}" aria-required="true" aria-invalid="false" data-attr-name="color">
                  </form>
               </div>
               <div data-role="add-to-links" class="actions-secondary">
                  <a href="#" class="action towishlist" title="Add to Wish List" aria-label="Add to Wish List" data-post="{&quot;action&quot;:&quot;http:\/\/127.0.0.1\/magento2252\/wishlist\/index\/add\/&quot;,&quot;data&quot;:{&quot;product&quot;:&quot;1225&quot;,&quot;uenc&quot;:&quot;aHR0cDovLzEyNy4wLjAuMS9tYWdlbnRvMjI1Mi93b21lbi90b3BzLXdvbWVuL2phY2tldHMtd29tZW4uaHRtbA,,&quot;}}" data-action="add-to-wishlist" role="button">
                  <span>Add to Wish List</span>
                  </a>
                  <a href="#" class="action tocompare" title="Add to Compare" aria-label="Add to Compare" data-post="{&quot;action&quot;:&quot;http:\/\/127.0.0.1\/magento2252\/catalog\/product_compare\/add\/&quot;,&quot;data&quot;:{&quot;product&quot;:&quot;1225&quot;,&quot;uenc&quot;:&quot;aHR0cDovLzEyNy4wLjAuMS9tYWdlbnRvMjI1Mi93b21lbi90b3BzLXdvbWVuL2phY2tldHMtd29tZW4uaHRtbA,,&quot;}}" role="button">
                  <span>Add to Compare</span>
                  </a>
               </div>
            </div>
         </div>
      </div>
   </div>
</li>

The code which I am applying is as below which is inside onclick function of optionclass:-

$widget.element.on('click', '.' + options.optionClass, function () {
            var prodId = $(this).attr('rel');
            $.ajax({ 
                        url: urlBuilder.build('swatch/index/product'),
                        data: {productId:prodId},
                        type: 'post',
                        success: function(result) { 
                            var flipsrc = result.flipsrc;
                            if(result.success != ''){
                                var urlsrc = $(this).closest('div.product-item-info').find('img.flip').attr('src');  
                                console.log(urlsrc);
                            }

                        } 
                    });
            return $widget._OnClick($(this), $widget);
        });

The output is undefined.

Tester
  • 157
  • 8
  • 1
    Could you make this example complete so that we could run that example? Is it is your javascript-part is incomplete and we can only guess how it is implemented. – Esko Sep 20 '18 at 11:57
  • 3
    What is "this" ? – kemicofa ghost Sep 20 '18 at 11:58
  • 1
    this is swatch-option, If I use this to get rel of this element it gives me correct result, if you want me to share the function of js, I can share, but it wont be of much of help. – Tester Sep 20 '18 at 12:01
  • 1
    I have update my answer and added the js function. – Tester Sep 20 '18 at 12:03
  • 1
    @PeterB I am getting the response correct, all I want is to get the src within my ajax response. – Tester Sep 20 '18 at 12:10
  • @Tester You apparently did not even read the page that I posted. You are using `$(this)` wrong (`this` has a different meaning when *inside* $.ajax) and that is what its accepted answer shows how to resolve. – Peter B Sep 20 '18 at 12:19
  • Yes Right, thanks to Kadeer for explaining here. I now better get the link you shared, Thanks @PeterB – Tester Sep 20 '18 at 12:30

1 Answers1

2

Inside the success callback, this has stopped referring to the same context at line 2. So store the intended this in a local variable, ex. _this.

$widget.element.on('click', '.' + options.optionClass, function () {
            var prodId = $(this).attr('rel');
            var _this = this;
            $.ajax({ 
                        url: urlBuilder.build('swatch/index/product'),
                        data: {productId:prodId},
                        type: 'post',
                        success: function(result) { 
                            var flipsrc = result.flipsrc;
                            if(result.success != ''){
                                var urlsrc = $(_this).closest('div.product-item-info').find('img.flip').attr('src');  
                                console.log(urlsrc);
                            }

                        } 
                    });
            return $widget._OnClick($(this), $widget);
        });
kadeer
  • 151
  • 1
  • 9
  • really good understanding of scope! – JosephDoggie Sep 20 '18 at 12:12
  • 1
    The code worked, I have multiple li, so this code won't break. Am I Right? – Tester Sep 20 '18 at 12:17
  • 1
    No it shouldn't thanks to the use of `.closest` and `find` in that order which keeps the search within the DOM subtree of each `div.product-item-info`. – kadeer Sep 20 '18 at 12:20
  • 1
    Thanks. So my question is not the duplicate of the question as shared above, or is it? Plus it is just the assigning of this in the variable that went wrong with my code. Please correct me if I am wrong in the above points. – Tester Sep 20 '18 at 12:25
  • 1
    @Tester down to it's fundamentals, that is without the HTML block that came with the question, it would honestly be considered similar. Also, yes, not assigning the `this` var is what broke the code in your case. This solution I must note is only one of the ways to fix your issue there. – kadeer Sep 20 '18 at 12:29
  • 1
    Yes that is what I thought so. – Tester Sep 20 '18 at 12:30