Osvaldo Fagundes Osvaldo Fagundes - 2 months ago 14
PHP Question

Ajax Mysql PHP How to show $_SESSION arrays result into DIV

My friends,

I´m facing some hard trouble with Ajax & PHP integration. I have a simple code as below that returns the data from database and shows into div class="item-list". When the user puts the quantity and clicks on submit button, the selected item is uploaded into div class="returned", like the "add item to cart" function. The code is working as well (add & remove from list), but only with refresh on page.
I saw many examples on web and I tried to adapt them to my code (today is my third day of fighting), but with no success. Could you please show to me a way to load the selected items into div class="returned" without refresh on page?

Best regards & thanks a lot!

<?php
session_start();

if(isset($_POST["add_to_table"])){
if(isset($_SESSION["dynamic_list"])){

$item_array_id = array_column($_SESSION["dynamic_list"], "item_id");
if(!in_array($_GET["idproduct"], $item_array_id)){
$count = count($_SESSION["dynamic_list"]);
$item_array = array(
'item_id' => $_GET["idproduct"],
'model' => $_POST["got_model"],
'price' => $_POST["got_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["dynamic_list"][$count] = $item_array;
}else{
echo'<script>alert("Item added!")</script>';
echo'<script>window.location="intransit.php"</script>';
}
}else{
$item_array = array(
'item_id' => $_GET["idproduct"],
'model' => $_POST["got_model"],
'price' => $_POST["got_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["dynamic_list"][0] = $item_array;
}
}

if(isset($_GET["action"])){
if($_GET["action"] == "delete"){
foreach($_SESSION["dynamic_list"] as $list => $values){
if($values["item_id"] == $_GET["idproduct"]){
unset($_SESSION["dynamic_list"][$list]);
echo'<script>alert("Item removed!")</script>';
echo'<script>window.location="intransit.php"</script>';
}
}
}
}
?>

<?php include"header.php" ?>
<div id="main_box">
<div id="moviment">
<div class="item_list">
<?php
$query = "SELECT * FROM products ORDER BY model ASC LIMIT 3";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0){

while($row = mysqli_fetch_array($result)){
?>
<div id="product_table">
<form method="post" action="intransit.php?action=add&idproduct=<?php echo $row["idproduct"]; ?>">
<span><img src="images/<?php echo $row["image"]; ?>" alt="motor" width="80" height="80" /></span>
<span>Model:&nbsp<?php echo $row["model"]; ?></span>
<span>Price:&nbsp<?php echo $row["unitprice"]; ?></span>
<input type="text" name="quantity" value="1" class="qty" />
<input type="hidden" name="got_model" value="<?php echo $row["model"]; ?>" />
<input type="hidden" name="got_price" value="<?php echo $row["unitprice"]; ?>" />
<input type="submit" name="add_to_table" value="Add Item" />
</form>
</div><!--end "product_table"-->
<?php
}
}
?>
</div><!--end "item_list"-->
<div class="returned">
<table>
<tr>
<th>Model</th>
<th>Qty</th>
<th>Price</th>
<th>Total</th>
<th>Action</th>
</tr>
<?php
if(!empty($_SESSION["dynamic_list"])){
$total = 0;
foreach($_SESSION["dynamic_list"] as $list => $values){
?>
<tr>
<td><?php echo $values["model"]; ?></td>
<td><?php echo $values["item_quantity"]; ?></td>
<td>$<?php echo $values["price"]; ?></td>
<td><?php echo number_format($values["item_quantity"] * $values["price"], 2); ?></td>
<td><a href="intansit.php?action=delete&idproduct=<?php echo $values["item_id"]; ?>">Remove</a></td>


</tr>
<?php
$total = $total + ($values["item_quantity"] * $values["price"]);
}
?>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">$ <?php echo number_format($total, 2);?></td>
<td></td>
</tr>

<?php
}
?>
</table>

</div>
</div>
</div>
<?php include"footer.php" ?>

Answer

I tried to make example less complicated and to make it work with code you already created.

if (isset($_POST['got_model'])) {
    $_SESSION["dynamic_list"][$_GET["idproduct"]] = array(
        'item_id'       => $_GET["idproduct"],
        'model'         => $_POST["got_model"],
        'price'         => $_POST["got_price"],
        'item_quantity' => $_POST["quantity"]
    );
    return show_dynamic_list();
}

if (isset($_POST["action"]) && $_POST["action"] == "delete") {
    unset($_SESSION["dynamic_list"][$_POST["idproduct"]]);
    return show_dynamic_list();
}

function show_dynamic_list(){
    ?>
    <table>
        <tr><th>Model</th><th>Qty</th><th>Price</th><th>Total</th><th>Action</th></tr>
        <?php
        $total = 0;
        foreach ($_SESSION["dynamic_list"] as $list => $values) {
            ?>
            <tr>
                <td><?php echo $values["model"]; ?></td>
                <td><?php echo $values["item_quantity"]; ?></td>
                <td>$<?php echo $values["price"]; ?></td>
                <td><?php echo number_format($values["item_quantity"] * $values["price"], 2); ?></td>
                <td>
                    <form action="" method="post" class="delete_form">
                        <input type="hidden" name="idproduct" value="<?php echo $values["item_id"]; ?>"/>
                        <input type="hidden" name="action"  value="delete"/>
                        <input type="submit"  value="Remove">
                    </form>
                </td>
            </tr>
            <?php
            $total = $total + ($values["item_quantity"] * $values["price"]);
        }
        ?>
        <tr>
            <td colspan="3" align="right">Total</td>
            <td align="right">$ <?php echo number_format($total, 2); ?></td>
            <td></td>
        </tr>
    </table>
    <?php
}



include"header.php" ?>
    <div id="main_box">
        <div id="moviment">
            <div class="item_list">
                <?php
                $query = "SELECT * FROM products ORDER BY model ASC LIMIT 3";
                $result = mysqli_query($connect, $query);
                if(mysqli_num_rows($result) > 0){
                    while($row = mysqli_fetch_array($result)){
                        ?>
                        <div id="product_table_<?php echo $row["idproduct"]; ?>">
                            <form method="post" action="?action=add&idproduct=<?php echo $row["idproduct"]; ?>">
                                <span>Model:&nbsp<?php echo $row["model"]; ?></span>
                                <span>Price:&nbsp<?php echo $row["unitprice"]; ?></span>
                                <input type="text" name="quantity" value="1" class="qty"/>
                                <input type="hidden" name="got_model" value="<?php echo $row["model"]; ?>"/>
                                <input type="hidden" name="got_price" value="<?php echo $row["unitprice"]; ?>"/>
                                <input type="submit" name="add_to_table" value="Add Item"/>
                            </form>
                        </div><<!--end "product_table"-->
                        <?php
                    }
                }
                ?>
            </div><!--end "item_list"-->
            <div class="returned">
                <?php show_dynamic_list(); ?>
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
    <script type="text/javascript">
        $(function () {
            $('body').on('submit','#moviment form,.delete_form',function (event) {
                event.preventDefault(); // Prevent the form from submitting via the browser
                var form = $(this);
                $.ajax({
                    type:'post',
                    url: form.attr('action'),
                    data: form.serialize(),
                    dataType:'html'
                }).done(function (data) {
                    $('.returned').html(data);
                }).fail(function (data) {
                    // error
                });
            });
        });
    </script>
<?php include"footer.php";
Comments