Ad

Ajax POST Request To Shopify's /cart/add.js Always Returning On Error Callback Function

- 1 answer

$.ajax({
                                    type: 'POST',
                                    url: '/cart/add.js',
                                    data: {
                                        quantity: 1,
                                        id: form_data
                                    },
                                    success: function(response) {
                                        console.log('in success');
                                        var url = $("#af-btn").attr("href");

                                        window.location.href = $("#af-btn").attr("href");
                                    },
                                    error: function(response) {
                                        console.log(response + "in error");
                                        var url = $("#af-btn").attr("href");

                                        //window.location.href = $("#af-btn").attr("href");

                                    },
                                    complete: function(response) {
                                        console.log(response);
                                    }
                                });

Above is my AJAX request. Below is the response Object.
Object Response shows 200 OK response
Add to cart to shows anonymous behavior, sometimes product gets added and sometimes product is not added. Can't figure it out. Any ideas?
Below is the form_data
Form Data
How I retrieve its value,

var form_data = $('form[action="/cart/add"]').find('select[name="id"]').find(":selected").val();
Ad

Answer

This is how I solved it for using the Shopify Ajax Api in Shopify app whose script was added through Shopify Admin API ScriptTag.

1- Load Shopify jQuery Ajax Api Wrapper

function loadShopifyAjaxApiScript()
{

var script = document.createElement("script");
script.rel = "text/javascript";
script.src = "https://cdn.shopify.com/s/assets/themes_support/api.jquery-0ea851da22ae87c0290f4eeb24bc8b513ca182f3eb721d147c009ae0f5ce14f9.js";
document.getElementsByTagName("head")[0].appendChild(script);

}

2- Then use it like below :

            Shopify.addItem(variantId , 1 , function () {
            console.log('success');
        });

Resource Link : API jQuery Ajax Shopify Sandbox

Ad
source: stackoverflow.com
Ad