skip to Main Content

I have an HTML that gets its values from an array list. I’m submitting the form with Ajax and with a PHP script. The issue I’m facing is when clicking on the other array it only submits the first value array. Below is what my form looks like with the PHP loop of array listing:

index.php


       
$query_product = "SELECT * FROM products ORDER BY id DESC";
$product_stmt = $conn->prepare($query_product);


if($product_stmt->execute()){
    while($row_product = $product_stmt->fetch(PDO::FETCH_ASSOC)){
    
    $id = $row_product["id"];
    $title = $row_product["title"];
    $description = $row_product["description"];
    $price = $row_product["price"];
    $img = $row_product["img"];
    
  
                         ?>

 <form onsubmit="clickButton()">
   <input type="hidden" value="<? echo $title ?>" name = "title" id="title" >
   <input type="hidden" value="<? echo $id ?>" name = "id" id="id" >
   <input type="hidden" value="<? echo $price; ?>" name="price" id="price">
  <input type="hidden" value="<? echo $img; ?>" 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>

<?php 
     }
  }


?>
                       

My Ajax looks like the below:


<script type="text/javascript">

function clickButton(){
   
     var title = $("#title").val();
 var price = $("#price").val();
 var img_src = $("#img_src").val();
 var id = $("#id").val();
    
alert(title);

      $("#add_to_cart").attr("disabled", true);
      
    $.ajax({
        type:"post",
        url:"my_add_cart.php",
        data: 
        {  
           'title' :title,
           'price' :price,
           'img_src' :img_src,
            'id' :id
        },
        cache:false,
        
         beforeSend: function(){
     $("#loading").show();
   },
   
   complete: function(){
     $("#loading").hide();
   },
   
 success: function (data) 
        {
         //   alert(data['message']);
          //enable loading 
             $("#add_to_cart").attr("disabled", false);
          
           $('#msg').html(data['message']);
           $('#count').html(data['count']);        
        }
        
    });
    return false;
 }
</script>



When I tried to alert(title); above it return just the first array value even though I click the other arrays.

2

Answers


  1. Chosen as BEST ANSWER

    So I was able to solve this myself by adding the ID of each item from the loop to the ID of the input form in the HTML making the ID of each item unique. Below is how I solved it:

    
    <form onsubmit="clickButton(<? echo $id ?>)">
    
    <input type="hidden" value="<? echo $title ?>" name = "<? echo $id.'_title' ?>" id="<? echo $id.'_title' ?>" >
                                                
    <input type="hidden" value="<? echo $id ?>" name = "<? echo $id.'_id' ?>" id="<? echo $id.'_id' ?>" >
                                             
    <input type="hidden" value="<? echo number_format($price); ?>" name = "<? echo $id.'_price' ?>" id="<? echo $id.'_price' ?>" >
    
    <input type="hidden" value="<? echo "url".$row_product_img[0]; ?>" name = "<? echo $id.'_img_src' ?>" id="<? echo $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(<? echo $id ?>);">Add Cart</button>
                                                  
    </form>
    
    

    And my Javascript is as below:

    
    <script type="text/javascript">
    
    function clickButton(id){
        var title=document.getElementById(id+'_title').value;
        var price=document.getElementById(id+'_price').value;
        var img_src=document.getElementById(id+'_img_src').value;
        var id=document.getElementById(id+'_id').value;
        
          $("#add_to_cart").attr("disabled", true);
          
        $.ajax({
            type:"post",
            url:"my_add_cart.php",
            data: 
            {  
               'title' :title,
               'price' :price,
               'img_src' :img_src,
                'id' :id
            },
            cache:false,
            
             beforeSend: function(){
         $("#loading").show();
       },
       
       complete: function(){
         $("#loading").hide();
       },
       
     success: function (data) 
            {
             //   alert(data['message']);
              //enable loading 
                 $("#add_to_cart").attr("disabled", false);
              
               $('#msg').html(data['message']);
               $('#count').html(data['count']);        
            }
            
        });
        return false;
     }
    </script>
    
    
    
    

  2. If you ignore the need for a form as you are using ajax you could streamline your code so that each record displays a single button that has various attributes set which are read by the javascript click handler and used to construct the payload sent via ajax to the php server.

    $query_product="SELECT * FROM products ORDER BY id DESC";
    $product_stmt = $conn->prepare( $query_product );
    
    if( $product_stmt->execute() ){
        while( $rs = $product_stmt->fetch( PDO::FETCH_ASSOC ) ){
            printf(
                '<input type="button" class="btn btn-outline-secondary btn-sm ajax" value="Add to cart" data-id="%s" data-title="%s" data-price="%s" data-img="%s" />',
                $rs["id"],
                $rs["title"],
                $rs["description"],
                $rs["price"],
                $rs["img"]
            );
         }
      }
    ?>
    
    
    <script>
    
        document.querySelectorAll('input.ajax').forEach( bttn => bttn.addEventListener('click',function(e){
            let fd=new FormData();
                fd.set( 'id', this.dataset.id );
                fd.set( 'title', this.dataset.title );
                fd.set( 'price', this.dataset.price );
                fd.set( 'img_src', this.dataset.img );
            
            alert( this.dataset.title );
            
            $.ajax({
                type:"post",
                url:"my_add_cart.php",
                data:fd,
                cache:false,
                beforeSend: function(){
                    $("#loading").show();
                },
                success:function( data ){
                    $("#add_to_cart").attr("disabled", false);
                    $('#msg').html(data['message']);
                    $('#count').html(data['count']);        
                },
                complete: function(){
                    $("#loading").hide();
                }
            });
        }))
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search