Re: Custom add to cart using ajax

Why am I getting a 400 error with custom 'add to cart' button using ajax?

Ritikaaaa
Shopify Partner
39 0 3

Hello,

I tried to add to cart product through custom button using ajax but i'm getting this error
/cart/add.js 400 (Bad Request) can anyone help me!!
Here is my code
<button class="add-to-cart-btn" data-product-id="{{ card_product.id }}">Add to Cart</button>
<script>
jQuery(document).ready(function($) {
$('.add-to-cart-btn').click(function(e) {
e.preventDefault();
let button = $(this);
button.text('Adding....')
let variantID = $(this).data('product-variant');
let quantity = 1;
$.ajax({
type:'POST',
url: '/cart/add.js',
data:{
quantity: quantity,
id: variantID
},
dataType: 'json',
success: function(response){
console.log(response)
fetch(window.Shopify.routes.root + 'cart.js')
.then(response => response.json())
.then(data => {
$('.cart-count-bubble span').text(data.item_count)
console.log(data)
});

button.text('Add to Cart');
}
});

});
});
</script>

Replies 5 (5)

Raj-WebDesigne
Shopify Partner
60 16 14
  1. Data attribute: In your button element, you're using data-product-id attribute, but in your JavaScript, you're trying to fetch data-product-variant. Make sure these match up correctly.

  2. Variant ID: Ensure that the variantID variable is correctly assigned. It should be fetched from the button's data attribute, so you might need to adjust the JavaScript code accordingly.

  3. URL: The URL /cart/add.js seems correct for adding a product to the cart in Shopify. However, if your store is set up differently, you might need to adjust this URL. Double-check that this is the correct endpoint.

  4. Data Format: Ensure that the data being sent in the AJAX request matches the expected format by the server. For Shopify, the expected format typically includes quantity and id fields. Check if the server expects any additional fields or if the field names need to be adjusted.

  5. Event Binding: Make sure that your jQuery event binding is correct and that the click event is being captured properly.

  6. Error Handling: Implement error handling in your AJAX request to better understand the reason for the "400 Bad Request" error. You can do this by adding a error callback function to your AJAX request and logging the error message.

    Here's a revised version of your code with some adjustments:

 

<button class="add-to-cart-btn" data-product-variant="{{ card_product.variant_id }}">Add to Cart</button>
<script>
jQuery(document).ready(function($) {
  $('.add-to-cart-btn').click(function(e) {
    e.preventDefault();
    let button = $(this);
    button.text('Adding...');
    let variantID = $(this).data('product-variant');
    let quantity = 1;
    $.ajax({
      type: 'POST',
      url: '/cart/add.js',
      data: {
        quantity: quantity,
        id: variantID
      },
      dataType: 'json',
      success: function(response) {
        console.log(response);
        // Update cart count
        fetch(window.Shopify.routes.root + 'cart.js')
          .then(response => response.json())
          .then(data => {
            $('.cart-count-bubble span').text(data.item_count);
            console.log(data);
          });
        button.text('Add to Cart');
      },
      error: function(xhr, status, error) {
        console.error(xhr.responseText);
        button.text('Add to Cart');
      }
    });
  });
});
</script>

 



If you require further help to optimize your store, please don’t hesitate to reach out.


This contribution will always benefit you and you will get my full help easily and you can contact me easily.


Your Willpower Contribution Link

:- Contribution

Contect On My Mail :-Mail@gmail.com


Ritikaaaa
Shopify Partner
39 0 3

Thanks but i still get this error: /cart/add.js 400 (Bad Request)
{"status":"bad_request","message":"Parameter Missing or Invalid","description":"Required parameter missing or invalid: id"}

Raj-WebDesigne
Shopify Partner
60 16 14

Please Check This one

  1. Missing or Invalid Variant ID: The error message indicates that the "id" parameter is missing or invalid. This likely refers to the variant ID of the product you're trying to add to the cart. Double-check that the "data-product-variant" attribute in your HTML button contains a valid variant ID.
  2. Check Variant ID Retrieval: Ensure that the line let variantID = $(this).data('product-variant'); correctly retrieves the variant ID from the button's data attribute. You can debug this by logging the value of variantID before making the AJAX request to see if it's correct.
  3. Verify Quantity: Make sure that the quantity being sent along with the AJAX request is valid. In your script, you're currently setting quantity to 1, but you may need to adjust this based on your requirements.
  4. Verify AJAX URL: Ensure that the URL being used in the AJAX request (/cart/add.js) is correct and corresponds to the endpoint for adding items to the cart in your Shopify store.
  5. Server-Side Validation: It's also possible that there's a server-side validation or configuration issue on the Shopify side causing the "Bad Request" error. Check Shopify's documentation or contact their support for any specific requirements or issues related to adding items to the cart via AJAX.

If you require further help to optimize your store, please don’t hesitate to reach out.


This contribution will always benefit you and you will get my full help easily and you can contact me easily.


Your Willpower Contribution Link

:- Contribution

Contect On My Mail :-Mail@gmail.com


Ritikaaaa
Shopify Partner
39 0 3

Not working 😞

tim
Shopify Partner
3911 395 1440

You should send items array as per https://shopify.dev/docs/api/ajax/reference/cart#post-locale-cart-add-js 

Also, it's not obvious what object is card_product  in your code, but you add to cart variants, not products, so be careful here as well.

 

If my post is helpful, consider liking it -- it will help others with similar problem to find a solution.
I can be reached via e-mail tairli@yahoo.com