0

I have a code which adds to cart using jQuery and php session.

Everything works fine except from display the status of the action of adding to cart. Such as "Added to cart" , "updated" etc.

The message is stored in the PHP variable called $status, and after Adding to cart, it's suppose to alert with jQuery saying item added successfully.

However I tried to alert another php variable outside of an if Statement and it works.. but the variable $status within the if Statements which adds item to cart doesn't display.. Here is my php code

<?php


    if (isset($_POST['pro_id']) && $_POST['pro_id']!=""){
  
    // declares variables
    
    if(!is_numeric($_POST['quantity']) || strval(intval($_POST["quantity"])) != strval($_POST["quantity"])) {

    $error = "Quantity must be interger";

} else {
    
    $pro_id = $_POST['pro_id'];
    $quantity = $_POST['quantity'];
    $option = $_POST['option'];
   
    // selects product details
    
    $sql = "SELECT * FROM products WHERE pro_id = ?";
            
    $stmt = mysqli_prepare($link, $sql);
    
    // Bind variables to the prepared statement as parameters
    
                mysqli_stmt_bind_param($stmt, "i", $param_id);
                
    // Set parameters
    
    $param_id = $pro_id;
                
    mysqli_stmt_execute($stmt);
                    
    /* get result */
                    
    $result = mysqli_stmt_get_result($stmt);
    
    
    // fetches result as assoc array
                    
    
    $row = mysqli_fetch_assoc($result);
    
    // store fetched results in variables
    
    $name = $row['pro_name'];
    $price = $row['pro_price'];
    $option = $_POST['option'];
    
    // selects product image from images table
    
    $sql_img = "SELECT * FROM pro_images WHERE pro_id= ? LIMIT ?";
    
    $stmt_img = mysqli_prepare($link, $sql_img);
    
    // bind parameters
    mysqli_stmt_bind_param($stmt_img, "ii" ,$param_pro_id, $param_limit);
    
    $param_pro_id = $pro_id;
    $param_limit = 1;
     
    mysqli_stmt_execute($stmt_img);
    
    $img_results = mysqli_stmt_get_result($stmt_img);
    
    $image_re = mysqli_fetch_assoc($img_results); // fetches image an array
    
    // stores fetched image in a variable
    
    $image = $image_re["pro_image"];
    
    // declares the fetched result into an array to store in session
     
    $cartArray = array(
     $name=>array(
     'name'=>$name,
     'pro_id'=>$pro_id,
     'price'=>$price,
     'quantity'=>$quantity,
     'option'=>$option,
     'image'=>$image)
    ); 
    
    
    // insert cart data into session for guest user into session
    
    if (isset($_SESSION["cart"]) && is_array($_SESSION["cart"])) {
    
    $array_keys = array_keys($_SESSION["cart"]);
    
    
    // checks if product already exists in cart and delivers message
    
                if(in_array($name, $array_keys)) {
                    
            $status = "Product updated in cart";
    
                } else {
                    
    // Product is not in cart so add it
    
            $_SESSION["cart"] = array_merge($_SESSION["cart"], $cartArray);
    
            $status = "Product added to cart";
    
    
                }
            } else {
                
    // There are no products in cart, this will add the first product to cart
              
    $_SESSION["cart"] = $cartArray;
    
    $status = "Product added to cart";
    
    }
    }
    
    
    }
    
  
    
    
    
    ?>

And here is my jQuery code

$(document).ready(function() {
        $('.add').click(function() {
            var pro_id = $(this).attr("id");
            var quantity = 1;
            
                $.ajax({
                    type: "POST",
                    url: "index.php",
                    data: ({
                        pro_id: pro_id,
                        quantity: quantity
                    }),
                    cache: false,
                    success: function() {
                    
   alert("<?php echo $status; ?>");
                    }
                });
        });
    });

PS: Both script are on the same page .

Alenros
  • 816
  • 7
  • 23
Browyn Louis
  • 218
  • 3
  • 14
  • You seem to not really understand how Ajax works. Your PHP needs to echo a value so it can be seen in the response to the Ajax. Then it will go into the variable which is provided to the "success" callback. Most tutorials would show you this. Don't forget the PHP is executed on the server and js is executed in the browser. These things happen at different times in your page's lifecycle – ADyson Jan 31 '21 at 12:20
  • 2
    You need do `echo $status;` at your backend and this will come as response inside success function then you can simply do `alert(response);` and also add parameter here `success: function(response) {..` – Swati Jan 31 '21 at 12:20

1 Answers1

1

The on-page jquery script is waiting for the $status variable response from the server-side php script. Right now the php script is not outputting anything.

Your php script needs to output the $status variable (using echo, for example).

Add the following to the end of your php script:

echo($status);

Replace the 'success' part of your ajax with this the following:

success: function(result) {
   alert(result);
}

(the first line will accept the php output into the 'result' variable, the second line will output the result variable via an on-page alert box)

Seeker
  • 57
  • 5