Home  >  Q&A  >  body text

How to submit a form How to get the session count without reloading the page when submitting the form

I created a form with a hidden input form that submits values ​​to a PHP script and stores each value in a session array by reloading the page using AJAX. It returns an HTML success alert message to <p id ="msg"></p>. I need information on how to send $count to <p id="count"></p> and success alert message to <p id=" msg"></pphpcngt phpcn cnendcphpcn in success:php dot help AJAX. I also want the success alert to disappear after showing for 3 seconds. Below is my code:

my_add_cart.php

<?php 
 session_start();

     $_SESSION['title'][]=$_POST['title'];
     $_SESSION['price'][]=$_POST['price'];
     $_SESSION['img_src'][]=$_POST['img_src'];
     
        $count = count($_SESSION["title"]);
echo $count;
     echo '<div class="alert">
  <span class="closebtn" onclick="this.parentElement.style.display=\'none\';">&times;</span> 
  <center>Product added successfully to cart.</center>
</div>';
exit();
?>

The above is my_add_cart.php, below is my HTML and javascript:

<script type="text/javascript">

function clickButton(){
    var title=document.getElementById('title').value;
    var price=document.getElementById('price').value;
    var img_src=document.getElementById('img_src').value;
   
    $.ajax({
        type:"post",
        url:"my_add_cart.php",
        data: 
        {  
           'title' :title,
           'price' :price,
           'img_src' :img_src
        },
        cache:false,
  
        success: function (html) 
        {
           $('#msg').html(html);
           
        
        }
        
    });
    return false;
 }
</script>

<html>
   <p id="msg"></p>
   <p id="count"></p>
       
<form onsubmit="clickButton()">

<input type="hidden" value="<? echo $title ?>" name = "title" id="title" >

<input type="hidden" value="<? echo number_format($price); ?>" name = "price" id="price" >

<input type="hidden" value="<? echo "https://mikeandcathy.com.ng/admin/UploadFolder/".$row_product_img[0]; ?>" name = "img_src" id="img_src">
                                        
<button type="submit" id="add_to_cart" name="add_to_cart" class="btn btn-outline-secondary btn-sm" value="Add to cart" onclick="return clickButton();">Add Cart</button>
  
</form>

</html>

P粉587780103P粉587780103178 days ago346

reply all(1)I'll reply

  • P粉329425839

    P粉3294258392024-03-29 14:57:24

    I recommend converting your server code to json api

    solution

    Change my_add_cart.php to this

     $count,
                'message' => '
    ×
    Product added successfully to cart.
    '; ] ); exit(); ?>

    Change your frontend code to this

    sssccc
    
    
       

    " name = "img_src" id="img_src">

    reply
    0
  • Cancelreply