Help with AJAX request

Asked

Viewed 109 times

0

I have this function that searches in the database the quantity of products in stock.

public function contarProduto() {
    try {
        $pdo = Conexao::getInstance();
        $sql = "select id_produto as produto, sum(quantidade) as quantidade from estoque where tipo = 'entrada' group by id_produto;";
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        $saida = array();
        $i = -1;
        while ($rs = $stmt->fetch()) {
            $i = $i + 1;
            $saida[$i] = array("id" => ($rs['produto']), "qtd" => utf8_encode($rs['quantidade']));
        }
        return $saida[0];
    } catch (Exception $ex) {
        echo $ex->getMessage();
    }
}

And this page that turns content into JSON

<?php
require_once 'Modelo/DAO/EstoqueDAO.php';
$estoque = new EstoqueDAO();
$jason = $estoque->contarProduto();

echo json_encode($jason);
?>

I have this code that makes an AJAX request only that returns all products, even passing a data which in this case is id:1

var t = {id: 1};
$.getJSON("http://localhost/impressoras/newEmptyPHPWebPage.php",t, function 
(d) {
console.log(d.qtd);
});

I need this requisition to return only the product that is sent by id. someone can help me?

In case when the customer chooses a product through a select, the quantity will automatically appear in the stock, so I cannot pass the id by sql.

1 answer

1

You must add the parameter id, passed in ajax request, to your query. One approach would be to change that line $jason = $estoque->contarProduto(); for $jason = $estoque->contarProduto($_GET['id']);.

And finally change its function to:

//receba o parametro id
public function contarProduto($idProduto) {
    try {
        $pdo = Conexao::getInstance();
        //aplique o parametro id na consulta, como você está usando prepare statement, altere para o group by para :id_produto
        $sql = "select id_produto as produto, sum(quantidade) as quantidade from estoque where tipo = 'entrada' group by  :id_produto ;";
        $stmt = $pdo->prepare($sql);
        //agora faça o bind com o variavel $idProduto
        $stmt->bindParam(':id_produto', $idProduto);
        $stmt->execute();
        $saida = array();
        $i = -1;
        while ($rs = $stmt->fetch()) {
            $i = $i + 1;
            $saida[$i] = array("id" => ($rs['produto']), "qtd" => utf8_encode($rs['quantidade']));
        }
        return $saida[0];
    } catch (Exception $ex) {
        echo $ex->getMessage();
    }
}
  • Hello, thanks for your attention. I need to pass the id through $.get because all of this has to happen without updating the page. When the customer chooses a product in a select will automatically appear the quantity available in stock, then I will take the product id that is in Selct and pass through the $.get

Browser other questions tagged

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