-1

enter image description here

I am trying to make a simple shop cart and add products from my modal to it by submitting the values with onclick add to cart function

Inside my details modal I have a form with option value attributes

 <form action="add_cart.php" method="post" id="add_product_form">
         <input type="hidden" name ="product_id" value ="<?=$id;?>">
         <input type="hidden" name="available" id="available" value ="">
        <div class="form-group">
         <div class="large-3 columns">
          <label for="quantity">Quantity:</label>
          <input type="number" class="form-control" id="quantity" name="quantity">
         </div>
        </div>
        <div class="large-3 columns">
         <label for="size">Size:</label>
         <select name="size" id="size" class="form-control">
          <option value=""></option>
          <?php foreach($size_array as $string) {
           $string_array = explode(':', $string);
           $size = $string_array[0];
           $available = $string_array[1];
           echo '<option value="'.$size.'" data‐available="'.$available.'">'.$size.' ('.$available.'Available)</option>';
          }?>

I send the user inputs from my modal with Ajax Function add_to_cart with method post to do the processing, ajax redirects me back to products page.

I get "was added to card" from add_cart.php

code line:

$_SESSION['success_launch'] = $product['title']. 'was added to your cart.';

But only empty strings inserted inside my database table cart

enter image description here

Inside my developer tools in browser I am getting Notice: Undefined index: product_id in add_cart.php on line 6 , also size ,available and quantity are also undefined. I can't find the solution to it.

This is what I tried in add_cart.php :

<?php

require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/konfiguracija.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/config.php';

$product_id = sanitize($_POST['product_id']);
$size = sanitize($_POST['size']);
$available = sanitize($_POST['available']);
$quantity = sanitize($_POST['quantity']);
$item = array();
$item[] = array (
   'id'      => $product_id,
   'size'    => $size,
   'quantity'   => $quantity,

);

$domain = ($_SERVER['HTTP_HOST'] != 'localhost')?'.'.$_SERVER['HTTP_HOST']:false;
$query = $veza->prepare("SELECT * FROM products WHERE id = '{$product_id}'");
$query ->execute();
$product = $query->fetch(PDO::FETCH_ASSOC);
$_SESSION['success_launch'] = $product['title']. 'was added to your cart.';

//check does cookie cart exist
if($cart_id != ''){
  $cartQ= $veza->prepare("SELECT * FROM cart WHERE id = '{$cart_id}'");
  $cart = $cartQ->fetch(PDO::FETCH_ASSOC);
  $previous_items = json_decode($cart['items'],true);
  $item_match = 0;
  $new_items = array();
  foreach ($prevous_items as $pitem){
     if($item[0]['id']==$pitem['id'] && $item[0]['size'] == $pitem['size']){
       $pitem ['quantity']= $pitem['quantity']+$item[0]['quantity'];
       if ($pitem['quantity']>$available){
         $pitem['quantity'] = $available;

       }
       $item_match = 1;
     }
     $new_items[] = $pitem;
  }
  if($item_match != 1){
    $new_items = array_merge($item,$previous_items);
  }

  $items_json = json_encode($new_items);
  $cart_expire = date("Y-m-d H:i:s", strtotime("+30 days"));
  $something=$veza->prepare("UPDATE cart SET items = '{$items_json}',expire_date= '{$cart_expire}'WHERE id ='{$cart_id}'");
  $something ->execute();
  setcookie(CART_COOKIE,'',1,'/',$domain,false);
  setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);

}else {

  //add cart inside database
  $items_json = json_encode($item);
  $cart_expire = date("Y-m-d H:i:s",strtotime("+30 days"));
  $smth=$veza->prepare("INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}')");
  $smth->execute();
  $cart_id = $veza>lastInsertId();
  setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}

?>
Lortnok
  • 49
  • 1
  • 9

1 Answers1

1

That warning message means that there was an attempt to access keys in an array that do not exist.

To see the content of the $_POST array, try to do:

<?php
var_dump($_POST);

If it's empty, most probably you're using the wrong form method or the wrong HTTP method. Try this:

<?php
var_dump($_GET);

You may also debug HTTP messages using the browser development tools or something like Insomnia.

Anyway, always check if the keys exist before trying to use them:

<?php
$requiredKeys = ['product_id', 'size', 'available', 'quantity'];
foreach ($requiredKeys as $key) {
    if (!isset($_POST[$key])) {
        // handle error here
    }
}

ADDED:

Make this change:

<?php

$requiredKeys = ['product_id', 'size', 'available', 'quantity'];
foreach ($requiredKeys as $key) {
    if (!isset($_POST[$key])) {
        http_response_code(400);
        header('Content-Type: application/json');
        echo json_encode(
            [
                 'errorMsg'     => "Missing key: $key",
                 'missingKey'   => $key,
                 'receivedPost' => $_POST, 
            ]
        );
        die();
    }
}

require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/konfiguracija.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/config.php';

$product_id = sanitize($_POST['product_id']);
// The rest of the code

Keep the added validation code. Never assume $_POST is not empty.

I also noticed there's something wrong here:

var data = jQuery('add_product_from').serialize();

It should have been something like this:

var data = jQuery('#add_product_from').serialize();

Notice that I added the "#". You were sending an empty POST data.

I believe it's better to put the attribute "id" in all the "input" fields, fetch each of their values, check that was done successfully and use the values to build an object that could be used by the jQuery.ajax function. If you have done that, validating everything, most probably you would have easily noticed the mistake.

ADDED

Also, if you read the jQuery.ajax documentation, you'll notice that the success function can have parameters. Add at least the first one in order to receive the response data. Use it to check if there's an unexpected response and debug.

Pedro Amaral Couto
  • 2,056
  • 1
  • 13
  • 15
  • I am using developer tools, because my ajax function is on success set to location.reload(); So I can only see in my dev tools the undefined errors, where should I set the var dump to see the content of the $_POST array ? – Lortnok Apr 01 '18 at 00:34
  • At the beginning of the script. Also add a line "die();" after the "var_dump($_POST);". Most probably you're using GET instead the correct POST HTTP method. When I mentioned the browser developer tools, I was referring to, for instance if you're using Chrome, the window or frame that appears when you select the "Inspect" menu option (right click). You can use it to check if you're using Ajax properly. The Insomnia REST client can also be very useful. You can see what happens when you send some specified HTTP messages to test REST services and others services used by Ajax functions. – Pedro Amaral Couto Apr 01 '18 at 00:44
  • See this: https://stackoverflow.com/questions/15603561/how-can-i-debug-a-http-post-in-chrome – Pedro Amaral Couto Apr 01 '18 at 00:45
  • I noticed that you said "(...) my ajax function is on success (...)". If that PHP code is run, most probably it will be assumed as a success, even when there's an error, because the server will send a 200 HTTP code, therefore "location.reload();" is called anyway. See this: https://stackoverflow.com/questions/3258634/php-how-to-send-http-response-code – Pedro Amaral Couto Apr 01 '18 at 00:51
  • I have edited my question, to provide more information. I am not getting any output with var_dump. I am using mozzila developer tools inside the browser. – Lortnok Apr 01 '18 at 00:56
  • I found the mistake and edited my answer. A "#" is missing. – Pedro Amaral Couto Apr 01 '18 at 01:36
  • Thank you , altho the database still remained empty, could you help me out with this ? – Lortnok Apr 01 '18 at 01:45
  • Since you're using PDO, use PDO::ERRMODE_EXCEPTION to throw exceptions and use them to debug (http://php.net/manual/en/pdo.error-handling.php). Create a separate question. I received an automatic warning ("Please avoid extended discussions in comments. Would you like to automatically move this discussion to chat?") – Pedro Amaral Couto Apr 01 '18 at 01:50
  • I don't know how to use chat to contact you if you are willing to help me and move the conversation over there ? – Lortnok Apr 01 '18 at 01:57
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/167990/discussion-between-pedro-amaral-couto-and-lortnok). – Pedro Amaral Couto Apr 01 '18 at 14:04
  • Please, make another Stackoverflow question with the relevant database table definition ("CREATE TABLE ...") and the PHP code. It's easier that way. – Pedro Amaral Couto Apr 01 '18 at 14:07
  • Here is my new issue : https://stackoverflow.com/questions/49605803/invalid-argument-supplied-for-foreach-inside-shopping-cart – Lortnok Apr 02 '18 at 07:18