'shopify cart not updating in realtime

I am trying to add a add to cart button on my collection page, it works normally when i click the button it takes me to the cart with the product added, but what i want is to work exactly like add to cart button in my product details page, i don't have much knowledge of ajax so whatever i tried till now is from the online documentation and stackoverflow answers.

But the problem is that it doesn't update my cart in realtime like it should i have to refresh the page to see my product in the cart sidebar.

Here is my button and ajax function:

<button class="btn btn--to-secondary btn--full product__add-to-cart-button{% if section.settings.enable_payment_button and current_variant.available and product.selling_plan_groups == empty %} shopify-payment-btn btn--secondary{% endif %}"
    data-cart-submit
    type="submit" name="add"
               id="addnowtocart" data-cart-submit class="btn btn--to-secondary btn--full product__add-to-cart-button{% if section.settings.enable_payment_button and current_variant.available and product.selling_plan_groups == empty %} shopify-payment-btn btn--secondary{% endif %}" 
             onclick="Shopify.addItem({{ product.variants.first.id }}, 1); return false"
    {% unless current_variant.available %} disabled="true"{% endunless %}
    aria-label="{{ button_text }}">
         Add to cart</button>

My AJAX call:

Shopify.addItem = function(variant_id, quantity, callback, attr) {

  var quantity = quantity || 0;
  if(typeof attr == 'undefined'){
    attr = [];
  }
  var params = {
    type: 'POST',
    url: '/cart/add.js',
    data: {quantity: quantity, id:variant_id,properties: attr},
    dataType: 'json',
    success: function(line_item) {

      if ((typeof callback) === 'function') {
        callback(line_item);
      } else {
       jQuery.get('/cart?view=json', function(data) {
         /*optional stuff to do after success */
        jQuery('.block-cart-list').html(data);
       });
       jQuery.getJSON('/cart.js', function(cart) {
          jQuery(".la-cart-count").html(cart.item_count);
        } );
      }
      {% if settings.g_add_to_cart_action == 'popup' %}
        Shopify.cartPopap();
      {% endif %}
      {% if settings.g_add_to_cart_action == 'fade_in' %}
        jQuery('#nova-notification .notification-content').html("The product <span>"+line_item.title+"</span> was added to your shopping cart.<br><a href=\"/cart\" class=\"button-readmore\">View Cart</a>");
        jQuery('#nova-notification').stop().fadeIn('slow', function(){
          setTimeout(function(){ jQuery('#nova-notification').stop().fadeOut('slow'); }, 4000);
        });         
      {% endif %}
    },
    error: function(XMLHttpRequest, textStatus) {
      Shopify.onError(XMLHttpRequest, textStatus);
    }
  };
  jQuery.ajax(params);
};


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source