I developed a shopping cart using jquery, ajax and json. It is working fine on local server in chrome. But when I run on server using chrome it is not doing anything; but running on firefox.

It is not running first time, but when I came back from another page then it runs.

JS CODE

<script>
function add_to_cart(cart_qty, cart_itemid)
{

    if(cart_qty<=0 || isNaN(cart_qty))
    {
    my_msg('Error', 'Incorrect Quantity');
    }
    else
    {
        $.ajax({  
            type: "POST",  
            url : "shopping_cart.php",  
            data: "cart_itemid="+cart_itemid+"&cart_qty="+cart_qty,
            success: function(json)
            {
                $("#shopping_cart").html('');
                var sub_total=0;
                $.each($.parseJSON(json), function(idx, obj) {
//              alert(obj.product_name);
                $("#shopping_cart").append(
                  '<div class="w50">'+obj.qty+' x </div>'+
                  '<div class="link"><a href="sub-category-detail-view.html">'+obj.product_name+'</a></div>'+
                  '<div style="clear:both"></div>');
                  sub_total += (obj.price * obj.qty);
//                alert(sub_total);
                });
                $("#sub_total").html('Sub-Total: Rs. '+sub_total);
                my_msg('Notification', 'Cart Updated Successfully !!');
                $("#msg").html('');
            },
            beforeSend: function()
            {
            $("#msg").html('<img src="loading.gif" align="absmiddle" alt="Loading...">');
            }
        }); 
    }

}
</script>

PHP CODE

<div style="background: #F7F7F7; border: 1px solid #DDDDDD; padding: 10px;">Qty:
<input type="text" name="qty" id="qty" size="3" value="1">
<a class="button" style="cursor:pointer;" onClick="add_to_cart($('#qty').val(),'<?php echo $fetchline['id'];?>')"><span>Buy</span></a>
<span id="msg" style="text-align:center; padding:6px; color:#EB679F; font-weight:bold; font-size:14px;"></span>
<br>
</div>

Check Live

Dani AI

Generated

Likely causes here are: Chrome is choking on the JSON, the request URL is resolving to the wrong path on the live site, or the first GET is being cached. is right that this is a state-changing action, so keep it as POST. And as @diafol noted, tell jQuery to expect JSON so you get a parse error instead of a silent failure. Also add an error callback and use an absolute URL to avoid the /product/ prefix issue.

Try this trimmed rewrite:

function add_to_cart(cart_qty, cart_itemid) {
  if (cart_qty <= 0 || isNaN(cart_qty)) {
    if (typeof my_msg === "function") my_msg("Error", "Incorrect Quantity");
    return;
  }

  $.ajax({
    type: "POST",
    url: "/shopping_cart.php",       // absolute path avoids /product/ relative lookups
    dataType: "json",                // jQuery will parse JSON or fail into error:
    data: { cart_itemid: cart_itemid, cart_qty: cart_qty },
    beforeSend: function () {
      $("#msg").html('<img src="loading.gif" alt="Loading...">');
    },
    success: function (items) {
      var sub_total = 0, $cart = $("#shopping_cart").empty();
      $.each(items, function (_, obj) {
        $cart.append(
          '<div class="w50">' + obj.qty + ' x </div>' +
          '<div class="link"><a href="sub-category-detail-view.html">' + obj.product_name + '</a></div>' +
          '<div style="clear:both"></div>'
        );
        sub_total += (obj.price * obj.qty);
      });
      $("#sub_total").text("Sub-Total: Rs. " + sub_total);
      if (typeof my_msg === "function") my_msg("Notification", "Cart Updated Successfully !!");
      $("#msg").empty();
    },
    error: function (xhr, status, err) {
      console.error("AJAX error:", status, err, xhr.responseText);
      $("#msg").text("Could not update cart.");
    }
    // If you switch to GET later, add: cache: false
  });
}

On the PHP side, return only JSON (no echoes, BOM, or notices) and set the header so Chrome knows what it is:

<?php
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($items);
exit;

If it still fails on some PCs, open DevTools in Chrome: check Network for shopping_cart.php (status 200 and valid JSON) and Console for JSON parse or 404 errors. These two views usually expose the exact issue within seconds.

Recommended Answers

All 10 Replies

You set type: "POST" but you're sending data:"cart_itemid="+cart_itemid+"&cart_qty="+cart_qty as if it were "GET" try replacing the type or changing how data is sent.

On another note, if you're already using jQuery, take a look at .post() in the documentation for a shortand ajax post request with callbacks.

Member Avatar for Member #120589

If you're retrieving JSON data, then $.getJSON may be more appropriate. However, it uses 'GET', so not appropriate if you are changing anything on the server e.g. manipulating DB data - for that, you should use 'POST' - possibly $.post as a shorthand to the more general $.ajax, as mentioned by Fernando_4.

I changed type; still not working..Actually, its not responsing anything.. Fernando_4 or diafol help me to rewrite my code.

Member Avatar for Member #120589

still not working

heh heh -welcome to the world of ajax! You've changed something, but we don't know what. Post your updated cade. Also it could be your php code - try running it as stand alone with hard coded POST or GET values (whichever you're using now). If using $.ajax you need to declare a datatype as json.

I changed type: "POST" to type: "GET"
If use datatype:json
then how I can use data: "cart_itemid="+cart_itemid+"&cart_qty="+cart_qty
which I'm requesting.

Member Avatar for Member #120589

I checked the link - it seems to be working?

Actually.. its working on some PCs but not on all.. I cleared all cookies on my PC still same problem..

Member Avatar for Member #120589

Hopw about clearing the cache?

I cleared all cache of my chrome browser .. still same problem..

Member Avatar for Member #120589

Unfortunately, I can't seem to replicate the issue. Anybody else?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.