PHP shopping cart - update cart with AJAX

Hi,
I have the javascript code below that gets triggered by an "add to cart" button.
I also include an external PHP file to pick up id, qty, specs from javascript and update the database.
Everything works fine, I just want to know how to do it with AJAX so that page page does not reload every time an item is added to the cart.

Thanks in advance for your feedback.


<a href="#" class="btnWrap"><input class="formbutton" name="additem" value="Add to Cart" type="button" onClick="javascript:AddItem('784',document.getElementById('qty1').value,document.getElementById('spec11').value,document.getElementById('spec21').value)"></a>
 

<script language="JavaScript">
            
            function AddItem(id, qty, spec1, spec2, mainmenu){      
          var item = id;
             var qty = qty;
            var spec1 = spec1;
            var spec2 = spec2;

                  if (qty == '1'){
                  alert(qty+" item will be added to your Shopping cart");
                  }
                  if (qty != '1'){
                  alert(qty+" items will be added to your Shopping cart");
                  }

            self.location = "/index.php?page_id=<?php echo $page_id; ?>&action=add_item&id="+item+"&qty="+qty+"&spec1="+spec1+"&spec2="+spec2;
            
            
            }
</script>


<?php //external PHP file
            
            switch($_GET["action"])
                        {
                              case "add_item":
                              {
                              AddItem($_GET["id"], $_GET["qty"], $_GET["spec1"], $_GET["spec2"],$_GET["comments"]);
                                    break;
                              }
                              case "remove_item":
                              {
                                    RemoveItem($_GET["id"],$_GET["spec1"],$_GET["spec2"] ,$_GET["comments"]);
                                    break;
                              }

                              ...
                   
                    function AddItem($id, $qty, $spec1, $spec2, $comments){
                              //code here that updates cart table....
       
                          }
       

?>
sabecsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kiran SonawaneProject LeadCommented:
Try adde below code in head tag and replace "content" in $("#content") with your id name where you want to show the response.


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
  <script>
    $(document).ready(function(){
      $(".btnWrap").click(function(){
        addToCart();
      });
    })
    function addToCart(){
      $.ajax({
        url: "/index.php?id=784&qty="+$("#qty1").val()+"&spec1="+$("#spec11").val()+"&spec2="+$("#spec21").val(),
        success: function(data){
          $("#content").html(data); // Replace "content" with id name where you want show the response
        }
      });
    }
    
     
  </script>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sabecsAuthor Commented:
Thanks sonawanekiran,
I ended up just using part of your code in my existing function which appears to be working great.

Is it possible to insert text "Item Added" into the div item_added and hide the Add to Cart button if the item has already been added to the cart?


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script language="JavaScript">
<!--

            //set specification to 1 which is the default or first color
            function AddItem(id, qty, spec1, spec2, mainmenu){      
              var item = id;
             var qty = qty;
            var spec1 = spec1;
            var spec2 = spec2;

            
                  $.ajax({
                  url: "/index.php?id="+id+"&action=add_item&qty="+qty+"&spec1="+spec1+"&spec2="+spec2, success: function(data){
                      $("#item_added"+id).append('Item Added');
                  }
                  });
            
            
            
            }
//-->

</script>


<div id="item_added<?php echo $id; ?>"></div>
         
<a href="#" class="btnWrap"><input class="formbutton" name="additem" value="Add to Cart" type="button" onClick="javascript:AddItem('<?php echo $id; ?>',document.getElementById('qty<?php echo $cnt; ?>').value,document.getElementById('spec1<?php echo $cnt; ?>').value,document.getElementById('spec2<?php echo $cnt; ?>').value)"></a>


</div>
0
Kiran SonawaneProject LeadCommented:
It is possible.

1) Below line of

$("#content").html(data); // Replace "content" with id name where you want show the response

Add

$("#item_added").html("Item Added"); // I am assuming div has id "item_added"

2) For hiding add to cart button
 
// Assuming your "Add To Cart" button has id "add_to_cart"
Check if ($("#content").length > 0)
  $("#add_to_cart").hide();

else
$("#add_to_cart").show();





0
Mark BradyPrincipal Data EngineerCommented:
If you save the file I have attached "miniajax.js" you can include it in the <head> tags of your page, then it is very easy to post the data to your php script using ajax. I have modified your javascript function to use ajax instead.

<script language="JavaScript">
           
            function AddItem(item, qty, spec1, spec2, mainmenu) {      
                  if (qty == 1) {
                  alert(qty+" item will be added to your Shopping cart");
                  }
                  if (qty > 1) {
                  alert(qty+" items will be added to your Shopping cart");
                  }
// this is where you use ajax to send the items.
ajax.post("your_PHPscript.php", orderDone, 'id=' + id + '&qty=' + qty + '&spec1=' + spec1 + '&spec2=' + spec2);
}

function orderDone(result){
if(result != ''){
alert('Your oder has been placed!');
}
}
</script>


That's all there is to it!  Your javascript code is a little messy. On your form you are sending a whole bunch of data to the function where you could get all that info directly from the function. Also, you have already got the variables inside the function name here     function AddItem(item, qty, spec1, spec2, mainmenu)

Then you set the variables again inside the function with these lines

var item = item;
var id = id;

etc..... You already have the variables so don't set them again it is redundant.
Also, you have a variable "mainmenu" in your function but you never use it anywhere? You also don't send anything to the function that 'mainmenu' will replace.

Finally and all this is just to help you out, when you call a javascript function you can leave out the "javascript:" part.

onClick="AddItem(id,info,spec1,spec2)"   etc.....

I hope this helps. Anyway, the new function will now send the data to your php script. You should get your php script to echo something after it has put the data into the shopping cart so this gets returned back to the javascript function orderDone(result)

That way you can use the result and show a message to the user to let them know it has been added.
Try not to do to many javascript "alert()' calls because they become very annoying for users.

miniajax.js
0
sabecsAuthor Commented:
Thank you for your help, it is very much appreciated.

I ended using code below which show/hides buttons when an item has been added.

function AddItem(id, qty, spec1, spec2){      

$.ajax({
      url: "/index.php?id="+id+"&action=add_item&qty="+qty+"&spec1="+spec1+"&spec2="+spec2, success: function(data){
      $("#itemadded"+id).show();
      $("#addtocart"+id).hide();
      }
      });
 }


<div class="itemadded_div" id="itemadded<?php echo $id; ?>" style="display:none"><img src="/images/form_button_item_added.png" width="136" height="33" alt="Item has been added to cart" /></div>

<div class="addtocart_div" id="addtocart<?php echo $id; ?>">
<a href="#" class="btnWrap"><input class="formbutton" name="additem" value="Add to Cart" type="button" onClick="AddItem('<?php echo $id; ?>',document.getElementById('qty<?php echo $cnt; ?>').value,document.getElementById('spec1<?php echo $cnt; ?>').value,document.getElementById('spec2<?php echo $cnt; ?>').value)"></a>
</div>

<div class="moreinfo_div" id="moreinfo<?php echo $id; ?>">
<a href="#" class="btnWrap"><input name="" type="button" class="formbutton" value="More Details" onClick="location.href='/index.php?page=item_details&id=<?php echo $id; ?>'"></a>
</div>
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
AJAX

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.