Retrieve data in Mysql DB using AJAX/PHP to create a badge containing DB item count

Asked

Viewed 1,376 times

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 &nbsp;</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...

  • 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.

  • Oops, I’ll test your tips!

  • It didn’t work, nothing shows up!

  • Because js/php is involved in <code>?

  • I don’t get it @Miguel!

  • has <code> in your code or put here just for example?

  • @Miguel, just for example

  • Whoa, guys, I still can’t get this code of mine to work!!

Show 4 more comments

3 answers

1

In your code jQuery has a key lock more than one opening.

With the correction it’s 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 identei your code and this way it became easier to find the leftover key lock.

In addition, I recommend that you remove "echo $Row ['Total'];" from your PHP code because it is not encoded as JSON in this line and this could generate an inconsistency when converting the JSON value to text in your AJAX request.

Edited:

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

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

By removing these tags and leaving the loading of badgewel.js last you inform that the loading of the page should be synchronous and therefore in the order you set the link of the page with your scripts.

Edited 2:

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

Unless your https page changes the address to an http version on this or another server that provides jQuery.

I hope I’ve helped.

  • Whoa, buddy! I don’t know what’s wrong, but it hasn’t worked yet. I’m sorry, but I’m kind of a beginner still and maybe I’m commenting on some silly slip-up.

  • I edited my question and put all my html so you can take a look to see if there is an error ok. I appreciate your help!

  • I saw here now in firebug that an error is occurring: Referenceerror: $ is not defined in $(Document). ready(Function()){. Note: I am loading jquery from a CDN.

  • I edited my reply with the possible solution, in view of his comment and Albo Vieira’s reply.

  • Oops, I had already changed this tmb and nothing!! It’s all right in the html tag p?

  • I found another problem. New edition added the answer.

Show 1 more comment

0

I just saw in the firebug that there is a error:

Referenceerror: $ is not defined in $(Document). ready(Function()){. NOTE: I am loading jquery from a CDN.

This is because you are loading your javascript before jquery.

  • Oops, I’ve changed the order and the firebug persists!!!

0

Boss I did so worked out here... Then fits your code.

I may be wrong, but in your code "data" is only declared for output and not to receive from php (I don’t know if this is it, is what I "think").

Then if you need to change the "php sql", pq I did with my tables.

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 help qq thing comments that adjusts agent...

  • Good evening, my friend, I’ve made your modifications, but you still haven’t trimmed anything. Strange pq when I only run php with echo it displays the value of the item I want in the database, but when I use html+ajax, it doesn’t scroll!!!

  • Well I really have no idea... If the jquery is declared, and it’s all satin I know...

Browser other questions tagged

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