2
I need to get an item count in my Mysql DB using ajax and php.
My ajax is like this:
<code>
$(document).ready(function(){
$('#badgewel').empty(); //Limpa a tabela
$.ajax({
type:'get', //método HTTP usado
dataType: 'json', //tipo de retorno
url: '../badge.php',//arquivo php onde serão buscados os dados
success: function(dados){
$('#badgewel').text(dados);
}
}
});
});
</code>
And my PHP file looks like this:
<code>
<?php
$con = mysqli_connect('XXXX','XXXXXX','XXXXX','XXXXXX');
if (!$con){
die('Não pode conectar:' .mysql_error($con));
}
mysqli_select_db($con,"badge");
$sql="SELECT
idProd,
COUNT(idProd) AS Total
FROM Produtos";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($result);
echo $row ['Total'];//testei a pagina badge.php e funcionou
echo json_encode($row);
mysqli_close($con);
?>
</code>
In HTML I have a snippet where the data will be displayed (a bootstrap badge):
<code>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>teste badge</title>
<link rel="stylesheet" href="css/style.css">
<link rel="author" href="humans.txt">
<script src="../js/badgewel.js" type="text/javascript" charset="utf-8" async defer></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"> </script>
</head>
<body>
<div>
<h3>Isso é um teste de badge</h3>
<span><label>Total </label><p id="badgewel" class="badge"></p>
</span>
</div>
</body>
</html>
</code>
Turns out it’s not showing anything, it had to show the total but nothing happens!
Does it work to exchange "$('#badgewel'). text(data);" for "$('#badgewel'). html(data);" ? My suggestion...
– Rodrigo Tognin
The SQL code could omit the first field as well, thus: "SELECT COUNT(idProd) AS Total FROM Products" - would return only one field with the count of records.
– Rodrigo Tognin
Oops, I’ll test your tips!
– Bene
It didn’t work, nothing shows up!
– Bene
Because js/php is involved in
<code>
?– Miguel
I don’t get it @Miguel!
– Bene
has
<code>
in your code or put here just for example?– Miguel
@Miguel, just for example
– Bene
Whoa, guys, I still can’t get this code of mine to work!!
– Bene