adi bon
adi bon

Reputation: 311

pass jquery array to php with json

I'm building a small shopping cart. Currently I'm trying to implement the checkout feature which checks each product's stock before proceeding to the payment page.

This while loop is displaying each row from the "shoppingcart" table:

while ($row = $result->fetch()) {
     echo '<table class="cart-row" cellspacing="0" cellpadding="0" width="100%">';
     echo '<tbody>';
     echo '<tr>';
     echo '<td width="75"><img border="0" width="59px" height="78px" title="" alt="" src=' . $row["ImagePath"] .'></td>';
     echo '<td width="203"><span class="itemElements itemName">'. $row["Name"] .'</span></td>';
     echo '<td width="203"><input type="submit" class="btnMinus linkbtnType2" value="-"><input type="submit" class="btnPlus linkbtnType2" value="+"></td>';
     echo '<td width="135"><span class="qtyNum">('. $row["Qty"] .')</span> <br />';
     echo '<input type="hidden" name="ProductId" class="ProductId" value='.$row["ProductId"].' />';
     echo '<span class="qtyRemoveLink"><input type="submit" class="btnRemove linkbtn" value="Remove"></td>';                            
     echo '<td width="180"><span class="itemElements orderStatus">In Stock Usually dispatched within 24 hours</span></td>';
                                    echo '<td width="175" class="itemPriceRow"><span id="itemPrice">€ '. $row["Price"]* $row["Qty"]  .'</span></td>';
      echo '</tr>';
      echo '</tbody>';
      echo '</table>';
      echo '<br>';                            
}

In that while loop a hidden input button's value is being loaded with the productId corresponding to that returned row.

Now I have this jQuery method which is supposed to read all the procuctId values in the page and store them in an array.

$('#btnCheckout').click(function () {
    var productId = new Array();
    var j = 0;
    $(".ProductId").each(function () {
        productId[j] == $(this).val();
        j++;
    });
    $.ajax({
        type: "POST",
        url: "functions/checkProductStock.php",
        data: {
            productId: JSON.stringify(productId)
        },
        success: function (msg) {
            alert(msg);
        }
    })
})

This method then passes those values to a PHP method:

<?php include "../config.php" ?>
<?php
    $productIds = json_decode($_POST['productId']);
    var_dump($productIds);
    //foreach loop that iterate through an array containing the product IDs and exexcutes the below method.
    foreach ($productIds as $productId)
    {
        $CartDAL = new CartDAL();
        $result = $CartDAL->get_ProductInCartById($productId, $_SESSION["username"]);   

        $result = $ProductsDAL->get_ProductById($productId);
        $rowProduct = $result->fetch();

          //Get Product Quatity Form Cart
          $qty = $row["Qty"];

          //Get Product Stock
          $stock = $rowProduct["AvailableStock"];   

          if($qty <= $stock)
          {
              $CartDAL->remove_ProductInCart($productId, $_SESSION["username"]);     
          }
          else
          {
              echo $rowProduct["Name"].' is out of stock!';
          }  
    }
?>

Somehow when I'm using firebug the only value that are passed to this method are productId=%5B%5D. FYI the values that are supposed to be passed are 1 and 2. Any ideas why the wrong values are being read and passed in the array? Or maybe I made a mistake in the above methods?

Upvotes: 0

Views: 1978

Answers (3)

lonesomeday
lonesomeday

Reputation: 237865

Andreas suggests that you need to do an assignment = rather than testing for equality with ==. This is correct, and I think the reason your code doesn't work. There is, however, a nicer way to structure the whole section of code, using jQuery's map function:

$('#btnCheckout').click(function () {
    var productId = $('.ProductId').map(function () {
        return this.value;
    }).get();

    $.ajax({
        type: "POST",
        url: "functions/checkProductStock.php",
        data: {
            productId: productId
        },
        success: function (msg) {
            alert(msg);
        }
    });
});

Note that I have also used the same technique as Kanishka, so you can access the values as $_POST['productId'].

Upvotes: 1

Kanishka Panamaldeniya
Kanishka Panamaldeniya

Reputation: 17576

simply you can do this

  data: { productId : productId },

that's it! now you can access it in PHP:

   <? $myArray = $_REQUEST['productId ']; ?>

also

var myJSONText = JSON.stringify(myObject);

So

['Location Zero', 'Location One', 'Location Two'];

Will become:

"['Location Zero', 'Location One', 'Location Two']"

Data can be returned from the server in a similar way. I.e. you can turn it back into an object.

var myObject = JSON.parse(myJSONString);

see this question

Passing JavaScript array to PHP through jQuery $.ajax

Upvotes: 1

Andreas Eriksson
Andreas Eriksson

Reputation: 9027

This is incorrect:

productId[j]==$(this).val();

You're doing an equality check == instead of an assignment =

Change to:

productId[j]=$(this).val();

Upvotes: 3

Related Questions