?
Solved

PHP shopping cart - update cart with AJAX

Posted on 2011-10-10
5
Medium Priority
?
938 Views
Last Modified: 2012-06-27
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....
       
                          }
       

?>
0
Comment
Question by:sabecs
  • 2
  • 2
5 Comments
 
LVL 17

Accepted Solution

by:
sonawanekiran earned 1200 total points
ID: 36940864
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
 

Author Comment

by:sabecs
ID: 36942036
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
 
LVL 17

Assisted Solution

by:sonawanekiran
sonawanekiran earned 1200 total points
ID: 36942051
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
 
LVL 20

Assisted Solution

by:Mark Brady
Mark Brady earned 800 total points
ID: 36942071
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
 

Author Closing Comment

by:sabecs
ID: 36945829
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

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses
Course of the Month13 days, 20 hours left to enroll

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question