• PHP Help
  • Loading DOM with additional data variables

I am able to load the cart in a popup window, however when I add something to a cart, I get the success popup window alerting me that something has been added but the cart always comes up empty. The session variables don't appear to be triggering. In the data post variables where I'm using jquery to add to cart in footer javascript, am I calling out the right atribute element in reference to var product_id = $(this).attr('id'); ?

ACTION.PHP - Session variables are created for cart

<?php session_start();
if(isset($_POST["action"]))
{
	if($_POST["action"] == 'add')
	{


	if(isset($_SESSION["shopping_cart"]))
	{
		$is_available = 0;
		foreach($_SESSION['shopping_cart'] as $keys => $values)
		{
			if($_SESSION['shopping_cart'][$keys]['product_id'] == $_POST['product_id'])
			{
				$is_available++;
				$_SESSION['shopping_cart'][$keys]['product_quantity'] = $_SESSION['shopping_cart'][$keys]['product_quantity'] + $_POST['product_quantity'];
			}
		}

		if($is_available == 0)
		{
			$item_array = array(
				'product_id'	=>	$_POST['product_id'],
				'product_name'	=>	$_POST['product_name'],
				'product_price'	=>	$_POST['product_price'],
				'product_quantity'	=>	$_POST['product_quantity']
			);
			$_SESSION['shopping_cart'][] = $item_array;
		}
	}
	else
	{
		$item_array = array(
			'product_id'		=>	$_POST['product_id'],
			'product_name'		=>	$_POST['product_name'],
			'product_price'		=>	$_POST['product_price'],
			'product_quantity'	=>	$_POST['product_quantity']
		);

		$_SESSION['shopping_cart'][] = $item_array;
	}
}

if($_POST['action'] == 'remove')
{
	foreach($_SESSION['shopping_cart'] as $keys => $values)
	{
		if($values['product_id'] == $_POST['product_id'])
		{
			unset($_SESSION['shopping_cart'][$keys]);
		}
	}
}
if($_POST['action'] == 'empty')
{
	unset($_SESSION['shopping_cart']);
}
}?>

ADD CART FORM AND FOOTER JAVASCRIPT - Index.php

<?php session_start();?>
<html>
<body>

echo '<input type="text" style="padding:5px;margin-left:6px;" size="2" name="quantity" id="quantity'.$a3["lessonid"].'" class="form-control" value="1" />
            <input type="hidden" name="hidden_name" id="name'.$a3["lessonid"].'" value="'.$a3["title"].'" />
        	<input type="hidden" name="hidden_price" id="price'.$a3["lessonid"].'" value="'.$a3["price"].'" />
            <input type="button" name="add_to_cart" style="padding: 5px; margin-top:5px;" class="add_to_cart" id="'.$a3["lessonid"].'" value="Add to Cart" /><br>';


</body>
</html>


<script>
$(document).ready(function(){
load_cart_data();

function load_cart_data()
{
	$.ajax({
		url:"fetch_cart.php",
		method:"POST",
		dataType:"json",
		success:function(data)
		{
			$('#cart_details').html(data.cart_details);
			$('.total_price').text(data.total_price);
			$('.badge').text(data.total_item);
		}
	})
}

$(document).on('click', '.add_to_cart', function(){
		var product_id = $(this).attr('id');
		var product_name = $('#name'+product_id+'').val();
		var product_price = $('#price'+product_id+'').val();
		var product_quantity = $('#quantity'+product_id).val();
		var action = 'add';
		if(product_quantity > 0)
		{
			$.ajax({
				url:"action.php",
				method:"POST",
				data:{product_id:product_id, product_name:product_name, product_price:product_price, product_quantity:product_quantity, action:action},
				success:function(data)
				{
					load_cart_data();
					alert("Item has been Added into Cart");
				}
			})
		}
		else
		{
			alert("Please Enter Number of Quantity");
		}
	});


$(document).on('click', '.delete', function(){
    var product_id = $(this).attr('id');
    var action = 'remove';
    if(confirm("Are you sure you want to remove this product?"))
    {
        $.ajax({
            url:"action.php",
            method:"POST",
            data:{product_id:product_id, action:action},
            success:function(data)
            {
                load_cart_data();

                alert("Item has been removed from Cart");
            }
        })
    }
    else
    {
        return false;
    }
});

$(document).on('click', '#clear_cart', function(){
    var action = 'empty';
    $.ajax({
        url:"action.php",
        method:"POST",
        data:{action:action},
        success:function()
        {
            load_cart_data();

            alert("Your Cart has been clear");
        }
    })
});

});

</script>

    Have you checked what is contained in the requests you are sending, and what the responses are? Is fetch_cart.php responding with what it should? Is the browser console reporting any error? At the moment you're having your success handler guess at the format it's receiving; are you sending the correct media type header for it to guess correctly? I think at the moment you keep being told that the "Item has been Added into Cart" because you have made no provision for it to tell you anything else.

    One thing I want to point out is that you shouldn't need to submitting the product name and price to the server; you should already have that information and be able to look it up given the product id.

      I included the cart inclusion html and fetch_cart.php below. The cart popup initiates and loads but obviously always get cart empty. I am not receiving any event handler browser errors that I can see. The number format that loads from my product db results is 0.00.

      
      <div id="popover_content_wrapper">
                      <span id="cart_details"></span>
                      <div align="center">
                          <a href="order_process.php" id="check_out_cart">
                              <span class="add-cart-but">Check out</span>
                          </a>
                          <a href="#" id="clear_cart">
                              <span class="add-cart-but">Clear</span>
                          </a>
                      </div>
                  </div>
      
      

      fetch_cart.php_

      <?php session_start();
      $total_price = 0;
      $total_item = 0;
      $output = '
      <div class="table-responsive" id="order_table">
          <table style="padding:20px;color:black; width:100%; border-style:solid; border: 1px; border-color:black;">
              <tr style="background-color:#E0E0E0; border-style:solid; border: 1px; border-color:black;">
                  <th width="40%">Product Name</th>
                  <th width="10%">Quantity</th>
                  <th width="20%">Price</th>
                  <th width="15%">Total</th>
                  <th width="5%">Action</th>
              </tr>';
      if (!empty($_SESSION["shopping_cart"])) {
          foreach ($_SESSION["shopping_cart"] as $keys => $values) {
              $output .= '
              <tr style="background-color:#EEEEEE; border-style:solid; border: 1px; border-color:black;">
                  <td>' . $values["product_name"] . '</td>
                  <td>' . $values["product_quantity"] . '</td>
                  <td align="right">$ ' . $values["product_price"] . '</td>
                  <td align="right">$ ' . number_format($values["product_quantity"] *
                  $values["product_price"], 2) . '</td>
                  <td><button name="delete" class="div_common" id="' .
                  $values["product_id"] . '">Remove</button></td>
              </tr>
              ';
              $total_price = $total_price + ($values["product_quantity"] *
                  $values["product_price"]);
      
          $total_item = $total_item + 1;
      }
      $output .= '
      <tr>
          <td colspan="3" align="right">Total</td>
          <td align="right">$ ' . number_format($total_price, 2) . '</td>
          <td></td>
      </tr>
      ';
      } else {
          $output .= '
          <tr background-color:#EEEEEE;>
              <td background-color:#EEEEEE; font-weight:normal;  colspan="5" align="center">
                  Your Cart is Empty!
              </td>
          </tr>
          ';
      }
      $output .= '</table></div>';
      $data = array(
          'cart_details' => $output,
          'total_price' => '$' . number_format($total_price, 2),
          'total_item' => $total_item
      );
      echo json_encode($data);?>
      
      

        As Weedpacket suggested, you should try and see if the POST data arriving in action.php is what you expect it to be and be sure that it is setting $_SESSION variable appropriately. One way you can do that is putting the contents of the POST data into a file, or perhaps writing little messages to a log file. You can use the file_put_contents function to create a simple logging function:

        function write_log($mesg) {
          // NOTE this file must be writable
          file_put_contents('/path/to/log/file.log', $mesg . "\n", FILE_APPEND);
        }

        You can write the POST array like so:

        write_log(print_r($_POST, TRUE));

          I placed the following code in the header of action.php to try and get POST readout. I set the permissions of file.log to 0777. After running the script, I checked the log file. It was empty so I guess the POST array isn't getting sent at all.

          In my jquery where I'm Adding an item to cart: var product_id = $(this).attr('id');, I tried just replacing this attribute with a number. var product_id = 4, and ran the script, then checked POST log file. Posts not being sent.

          
           $root = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);
          
          function write_log($mesg) {
              // NOTE this file must be writable
              file_put_contents("".$root."/file.log", $mesg . "\n", FILE_APPEND);
          }
          write_log(print_r($_POST, TRUE));
          
          

            the variable $root will not be defined inside your function write_log unless you declare it as a global.

            function write_log($mesg) {
                global $root;
            
                // NOTE this file must be writable
                file_put_contents("".$root."/file.log", $mesg . "\n", FILE_APPEND);
            }

            PS: you might want to check the /file.log at the root of your filesystem. If file_put_contents failed, there should have been some kind or error emitted, I think?

            PHP Warning: file_put_contents(/file.log): failed to open stream: Permission denied in /tmp/foo.php on line XXX

            sneakyimp unless you declare it as a global

            Or preferably (IMHO) pass it in as an additional function argument. 😉

              It's returning an empty array. I'm narrowing the issue down to the following line, but even when substituting the attibute id with a number it returns an empty array. Am I calling out the id correctly in the button html?

              $(document).on('click', '.add_to_cart', function(){
              		var product_id = $(this).attr('id');
              		
              <input type="button" name="add_to_cart"  id="'.$a3["lessonid"].'" style="padding: 5px; margin-top:5px;" class="add_to_cart" value="Add to Cart" /><br>';
              
                2 years later
                Write a Reply...