Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very simple ajax add to cart

Tags:

jquery

ajax

php

Ok I am trying to wrap my head around how to add something to a cart and have it show in the page without reloading the page.

So I have tried to write something very simple so I can wrap my head around how exactly the logic works and is properly written. In my example I have a div in the page for the session['cart'] and a drop down.

One option with value of 'red' and the other option with value 'blue'. When I select the option with value of 'red', I want 'red' to show in the div located right after body tag insession['cart']. When I select the option with value of 'blue', I want 'blue' to show in session['cart'].

I am attempting to do this through an ajax post to a page called 'cart_update.php'. I have been struggling with a more advanced model of this for a week and I thought it would be a good idea just to write something simple so i could really understand and learn what is really going on. Any help is really appreciated!

Here is my code and I know its way off. I am just trying to learn.

index.php

        <?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<style type="text/css">
body {
    margin-top: 200px;
}
</style>
</head>

<body>
<div align="left" style="display:block;width:200px;height:200px;background:#ccc;border:solid 1px #009966;">Color Chosen<br /><?php echo $_SESSION['cart']; ?></div>

<div align="center"><form method="post" action="">
<select id="color-selection">
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
</div>
<script type="text/javascript">
$(document).ready(function(){
    $("#color-selection").on("change", function(event){
        var color = $("#color-selection").val();
        var add = "add";
        var dataString = {color: color, type: add}; //JSON-formatted string
        $.ajax({  
            type: "POST",  
            url: "cart_update.php",  
            data: dataString
        });
    });
});
</script>

</body>
</html>

and here is my cart_update.php

<?php
session_start();
$type = json_decode($_POST['type']);
if(isset($_POST["type"]) && $_POST["type"]== $type)
{
    $color = json_decode($_POST['color']);   
    $_SESSION['cart'] = $color;
}
?>
like image 994
DSmith Avatar asked Nov 23 '22 18:11

DSmith


1 Answers

It's hard to tell what's not working when you don't tell us what error/warning you get. You should look into your js-console (with firebug or another debugging tool)

Looking at your code though, I see some things..

$(document).ready(function(){
    $(".add_to_cart").onClick(function(){
         var dataString = "color=" + color;
          $.ajax({  
          type: "POST",  
          url: "cart_update.php",  
          data: dataString
          });
    });
});

onClick won't work in this context. Use on() instead. http://api.jquery.com/on/ The second thing is that you should use JSON-formatted strings when sending data.

$(document).ready(function(){
    $(".add_to_cart").on("click", function(event){
        var dataString = {color: color}; //JSON-formatted string
        $.ajax({  
            type: "POST",  
            url: "cart_update.php",  
            data: dataString
        });
    });
});

In your html you have hidden fields with several forms with defined colors. Instead of that approach I would make a select-list within one form so it would be kind of easy to grab the value of the color, and you wouldn't have to create a new form for each color.

Something like this:

<select id="color-selection">
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>

Then in your js, you can get the selection of color by doing something like this:

color = $("#color-selection").val();

To get a response-value when ajax-call is done, then use the done()-callback. It's also a good practice to assign a return-type.

$(document).ready(function(){
    $(".add_to_cart").on("click", function(event){
        color = $("#color-selection").val();
        var dataString = {color: color}; //JSON-formatted string
        $.ajax({  
            type: "POST",  
            url: "cart_update.php",  
            data: dataString,
            dataType: "json" //This indicates the expected return-type
        }).done(function(data) {
                $("#thecoloris").html(data.color); //response from php. Set the color in the div id="thecolorid"
       }); 

    });
});

In your php-code you will have to decode the json-data:

<?php
session_start();
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
    $color = json_decode($_POST['color']);   
    $_SESSION['cart'] = $color;
}
echo $_POST['color']; //Output color (that is sent to this php through ajax) - This acts as the return value data in the ajax-function done()
?>

Usually the outputted value should be encoded in json-format with json_encode($variable) but in this case $_POST['color'] is already in json-format because it was sent to the php from js in json-format.

like image 99
bestprogrammerintheworld Avatar answered Feb 20 '23 06:02

bestprogrammerintheworld