wsgg wsgg - 4 months ago 35
JSON Question

get json data from just one product in shopify

what im trying to do:

when i click a product in the collections page grid, i'm trying to get the product's title, etc using ajax.

heres my code:

{% for product in collection.products %}

<div class="product">
{% capture producturl %}{{ product.url }}{% endcapture %}
<a class="ajax ajax{% increment ajaxno %}">
PRODUCT IMAGE
</a>
</div>


<script>
jQuery(function ($) {

$("a.ajax0").click(function(){
jQuery.getJSON('{{ producturl }}.js', function(product) {
console.log('The title of this product is ' + product.title);
} );
});

});
</script>

{% endfor%}


but when i click on the any product, im getting alerts for all the products on the current page.
how do i tweak my code to only get the title of the product for the one i'm clicking?

Answer

You can do this without using AJAX:

{% for product in collection.products %}
  <div class="product">
   <a class="product-image" data-title="{{product.title}}">
    PRODUCT IMAGE 
   </a> 
  </div>
{% endfor%}

<script>
  jQuery(function($) { 
    $("a.product-image").click(function() {
      console.log($(this).data('title'));
    });
  });
</script>

If for some reason you prefer to use AJAX, this should work properly:

{% for product in collection.products %}
  <div class="product">
   <a class="product-image" data-url="{{product.url}}">
    PRODUCT IMAGE 
   </a> 
  </div>
{% endfor%}

<script>
jQuery(function($) {
  $("a.product-image").click(function(){
    var productUrl = $(this).data('url');
    jQuery.getJSON(productUrl + '.js', function(product) {
      console.log('The title of this product is ' + product.title);
    } );
  });
});
</script>