+ 1

php help

The purpose of my code is that when one clicks the button 'add to cart', the product name is stored in an array that is acting as a cart. Then i have another function, that when i click the button 'show cart' , it should show all the elements added in the array but it is not working, pls help <html> <head> </head> <body> <button onclick="showCart()">show cart</button> <?php session_start(); $conn =mysql_connect('127.0.0.1','root','123','shop'); //mysql Connection $result=mysql_query("select * from bookshop.books"); //sql statement ?> <?php while($row = mysql_fetch_array($result)){ ?> //while loop to enable access of data in database. <div> <img src="<?php echo $row['images']; ?>"> <button onclick="cart()">Add to cart</button> </div> <?php $cars = array(); //establishes an array echo '<script>'; echo 'function'.' '.'cart(){'; array_push($cars,"gg"); // adds elements to array echo 'alert("Your product was added");'; echo '}'; echo 'function'.' '.'showCart(){'; $arrlength = count($cars); // getting length of array for($counter = 0; $counter< $arrlength; $counter++) { // displays products in array echo 'alert('.$cars[$counter].');'; } echo '</script>'; } ?> </body> </html>

13th Jun 2018, 4:39 PM
Mogammad Shameer Losper
Mogammad Shameer Losper - avatar
3 Réponses
+ 2
If you take a look at your source code with developer tools I bet that you see that your cart() function has only alert function in it. You can't mix PHP and javascript like that. array_push() function is not executed when user clicks the button. It's executed immediately when user visits the page. So you should store the cart array in session variable and send the new item with ajax. Same goes for showCart() function. It should also be done with ajax <script> function cart(item) { $.ajax({ type: "POST", url: "cart_item.php", data: {item:item}, success: function(data) { alert(data) } }); } </script> cart_item.php session_start(); if(isset($_POST["item"])) { array_push($_SESSION["card"], $_POST["item"]); echo "Your product was added"; } Also your item should be an array which contains the name, image, price etc...
13th Jun 2018, 4:52 PM
Toni Isotalo
Toni Isotalo - avatar
+ 1
Ah so i have to learn Ajax as well, thank you so much. Did you just add ajax to my code? Do you mind if i use the corrections you made to my code lol? it will save me time as im currently feeling lazy.
13th Jun 2018, 5:23 PM
Mogammad Shameer Losper
Mogammad Shameer Losper - avatar
0
Mogammad Shameer Losper It was more like an example but let me know if you’re missing something.
13th Jun 2018, 5:59 PM
Toni Isotalo
Toni Isotalo - avatar