Get data in Mysql DB using AJAX / PHP to create a badge containing the DB item count [closed]

2

I need to get a count of items in my Mysql DB using ajax and php.

My ajax looks 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 section 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éumtestedebadge</h3><span><label>Total&nbsp;</label><pid="badgewel" class="badge"></p>
    </span>
    </div>


    </body>
    </html>

</code>

It happens that it is not displaying anything, it had to display the total but nothing happens!

    
asked by anonymous 08.07.2016 / 05:43

3 answers

1

In your jQuery code, you have a key lock more than an opening.

With the correction it looks like this:

$(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);
        }
    });
});

Note that I've iden- tified your code and this way it was easier to find the leftovers at the closing of the keys.

I also recommend that you remove the "echo $ row ['Total'];" of your PHP code as it is not encoded as JSON in this line and this could lead to an inconsistency in converting the JSON value to text in your AJAX request.

Edited:

On the error persist after changing the order of the files (first putting jQuery and then badgewel.js:

Remove the "async defer" modifier from the badgewel.js script, as this is loaded asynchronously. The browser can interpret this in a number of ways, depending on the implementation, but in general it loads asynchronously, ie it may still clutter in the head of your page to load before the jQuery script.

Removing these tags and leaving the badgewel.js load last lets you know that the page load should be synchronous and therefore in the order that you set the page link with your scripts.

Edited 2:

I noticed that you are including jQuery through a secure URL (https). The correct thing is to include the file according to the protocol of your page, otherwise there is no guarantee that it will be loaded.

Unless your page uses https, change the address to a version with http on this or another server that makes jQuery available.

I hope I have helped.

    
08.07.2016 / 06:37
0

I saw here now in firebug that a error is occurring:

  

ReferenceError: $ is not defined in $ (document) .ready (function ()) {. Note: I'm loading jquery from a CDN.

This is because you are loading your javascript before jquery.

    
08.07.2016 / 16:22
0

Boss made it work so well here ... It fits in your code.

I can be wrong, but in your code "data" is only declared for the output and not for receiving from php (I do not know if this is what I "think").

html.php

<html>
<head>
<meta charset="utf-8">
<title>teste badge</title>
<link rel="author" href="humans.txt">
<script type="text/javascript"  src="jqueryfull.js"></script><!--meu jquery-->
<script src="js.js" type="text/javascript" charset="utf-8"></script><!--o js-->

</head>
<body>
<div>
<h3>Isso é um teste de badge</h3>
    <span><label>Total &nbsp;</label><p id="badgewel" class="badge"></p>
</span>
</div>


</body>
</html>

js.js

$.post('php.php', $("#badgewel").serialize(), function(data) {
$('#badgewel').html(data);
$('#badgewel').text(data);
});

php.php

<?php 
$con = mysqli_connect('localhost','root','','test');
if (!$con){
die('Não pode conectar:' .mysql_error($con));
}

mysqli_select_db($con,"test");
$sql="SELECT nome_carac FROM carac";
$result = mysqli_query($con,$sql);

while( $row = mysqli_fetch_assoc($result) ){ 
   echo $row["nome_carac"];
   echo json_encode($row);
}
mysqli_close($con);
?>

See if anything helps what agent adjusts ...

    
09.07.2016 / 17:50