Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

97
Visualizações
ajax call returns only last id

I am trying to develop an add to cart function via ajax, the problem is that no matter which product I add to cart, it adds the last item on the list and then increments the same product upon clicking on any other product. Here is my code:-

<?php         
   $i = 1;
   while($row = mysqli_fetch_array($run_products)){  
     $op_id = $row['option_id'];

     echo "<tr>";
     echo "<td>" . $i . "</td>";
     echo "<td>" . $row['option_desc'] . "</td>";    
     echo "<td> 

     <form action='' method='post' class='p_form'>
       <input type='text' name='product_id' value='$op_id'  pid='$op_id'>
       <input type='text' name='quantity' value='1'  pid='$op_id'>
       <input class='btn btn-primary add' type='submit' name='add_to_cart' value='Add to Cart' id='product' pid='$op_id'>
     </form>
   </td>";
   echo "</tr>";        
   $i++;
 }
 ?>

Here is jquery:

<script type="text/javascript">

$(document).ready(function(){

    $(document).on('click','.p_form',function (event) {    
        event.preventDefault();

        var element = $(this);
        var id = element.attr("pid");
         //alert(id);

              $.ajax({

                  url: 'action.php',
                  method: 'post',
                  //data: {id:id}, 
                  data:$('.p_form').serialize(), 
                  success: function(data){

                      $('#message').html(data);                          
                  }
              });

        return false;

    });

});
</script>

Here is action.php, the $product_id always returns as 4 (for example) if the last id in the last is 4

if (!empty($_POST)){
    $product_id = $_POST['product_id'];
    echo $product_id;
}
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Need to do it like below:-

<script type="text/javascript">

$(document).ready(function(){
    $(document).on('click','.add',function (event) {//instead of form click add event on form button click    
        event.preventDefault();
        var element = $(this);
        var id = element.attr("pid");
        //alert(id);

          $.ajax({
              url: 'action.php',
              method: 'post',
              data:element.parent('.p_form').serialize(), //serialize clicked button parent form
              success: function(data){
                  $('#message').html(data);                          
              }
          });
        return false;
    });
});
</script>
about 4 years ago · Santiago Trujillo Relatório

0

Trigger click event on button click not on the form click:

This will work for you for each product.

<script type="text/javascript">

$(document).ready(function(){

    $(document).on('click','.add',function (event) {    
        event.preventDefault();

        var element = $(this);
        var id = element.attr("pid");
         //alert(id);

              $.ajax({

                  url: 'action.php',
                  method: 'post',
                  data: {id:id}, //send id of product you wish to add
                  success: function(data){

                      $('#message').html(data);                          
                  }
              });

        return false;

    });

});
</script>

And on server side:

if (!empty($_POST)){
    $product_id = $_POST['id'];//get only that id posted in ajax call
    echo $product_id;
}
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda