Find an input value within an AJAX loop

Asked

Viewed 38 times

0

I confess that I have been for a while in this small challenge, I am developing the cart part in my Ecommerce.

The goal is to display a message, the user click on "Add to cart" of a particular product.

The problem, is that I’m just getting to take and display the value of the first product that is displayed on my page (the other products, does not display message).

I am displaying the products through a foreach, and put their ID inside a input.

I think the problem lies in the way I’m calling mine function.

What could I be doing to solve this problem of mine?

PHP:

$connect = new PDO("mysql:host=localhost;dbname=ecommerce", "root", "");

$query = "SELECT * FROM produtos";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();

foreach($result as $cont){
?>

<h6><?=$cont['produto']?></h6>                                      // Nome dos produtos
<input type="hidden" id="id" value="<?=$cont['ID_detalhes']?>">     // Estou buscando esse value...
<a href="#" id="adicionar_carrinho">+ Adicionar ao carrinho</a>     // Botão que chama a função ajax
    
<?php } 

AJAX:

<script>
  $('#adicionar_carrinho').on('click', function(){
    $.ajax({
        url: 'verificar-carrinho.php',
        data: {ID_detalhes: $('#id').val()},
        method: 'POST',
        success:function(data){
              $('#msg_carrinho').html(data);  // Aqui é exibe a mensagem na tela
        }
    })  
});
</script>

check-cart.php:

if(isset($_POST['ID_detalhes'])){
        
echo "Produto (".$_POST['ID_detalhes'].") foi adicionado ao seu <b>carrinho</b>!";
}

I started working with AJAX recently, I appreciate the help of all!

2 answers

1

You are using id can only require one per page, they should be unique. Moreover, if there are several #id and several #adicionar_carrinho you must have some system to identify which of them was clicked (in this case taking the relative’s or the nearest).


Exchange the id for class or any other attribute.

let produtosAdd = window.document.querySelectorAll("produto [add]")
for (i = 0; i < produtosAdd.length; i++) {
  produtosAdd[i].addEventListener("click", function(e) {
    e.preventDefault();
   
    if ((id = e.target.previousElementSibling).hasAttribute("identifier")) {
      if (id instanceof HTMLInputElement) {
        alert("Adicionar o " + id.value + " no carrinho");
      }
    }
  })
}
<produto>
  <input type="hidden" identifier value="1">  
  <a href="#" add>+ Adicionar ao carrinho</a>
</produto>
<produto>
  <input type="hidden" identifier value="2"> 
  <a href="#" add>+ Adicionar ao carrinho</a>
</produto>

In this case the only difference is removal of the id (attribute) and use the function to pick up the relative value.


PS: I don’t know how to use Jquery (and there are no Jquery tags in your question), so I used pure JS.

1


$(function(){
  $(".adicionar_carrinho").on('click', function(e){
    e.preventDefault();
    let i = $('.adicionar_carrinho').index(this);    
    alert($('.produto').eq(i).val())
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <h6>PRODUTO 1</h6>
  <input type="hidden" class="produto" id="id1" value="Detalhe Produto 1">
  <a href="#" class="adicionar_carrinho">+ Adicionar ao carrinho</a>
</div>
<div>
  <h6>PRODUTO 2</h6>
  <input type="hidden" class="produto" id="id2" value="Detalhe Produto 2">
  <a href="#" class="adicionar_carrinho">+ Adicionar ao carrinho</a>
</div>
<div>
  <h6>PRODUTO 3</h6>
  <input type="hidden" class="produto" id="id3" value="Detalhe Produto 3">
  <a href="#" class="adicionar_carrinho">+ Adicionar ao carrinho</a>
</div>

  • The id must be unique, so you can put it like this: <input type="Hidden" id="id-<?= $cont['ID']? >" value="<?= $cont['Id_details']? >">. You want when clicking on the product to show the ID?

  • I got what I wanted, buddy, thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.