skip to Main Content

when I click on product title then I want to get product id and then post product id to another URL and get related product id from the database.

<script>
var a = window.location.href;
    $.ajax({
        type: "GET",
        dataType: "json",
        success: function (data) {
            var id = data.product.id;
            console.log(id);// i got product id but how i post this id to another url and get related product id from database.
        }
    });

2

Answers


  1. Do this:

    <script>
    var a = window.location.href;
        $.ajax({
            type: "GET",
            dataType: "json",
            success: function (data) {
                var id = data.product.id;
                $.post("{{url('productIdApi')}}", {product_id: id}, function(result){
                   //do whatever after response returns
                });
            }
        });
    
    Login or Signup to reply.
  2. The correct pattern for this is to render the product ID in Liquid to a JS variable. You understand Liquid has a JSON filter too right? So that means making an AJAX call to get the product info is redundant and a waste of time.

    Once you have the product ID in JS world, you cannot securely use it to call for related products unless you use an App Proxy. Shopify ensures your Ajax callback comes from the shop and is legit. Calling back to your own database without that is silly as anyone can then hack your data for any other use.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search