AJAX appear Divs according to database ID (MYSQL)

Asked

Viewed 476 times

2

I’m trying to do that every time I squeeze in #buttonIdUltimoItem a structured DIV appears taking information from database from the younger to the older according to the ID. The problem that instead is always repeating the last three Ids

BUTTON:

<button type="button" id="buttonIdUltimoItem" onClick="pegaDados();" value="<?= $idUltimoItem;?>">CARREGA +</button>

SCRIPT:

  <script>

var corpo = ""; //define a variavel corpo como global


function pegaDados()
{
    var idUltimo = $("#buttonIdUltimoItem").val();
    jQuery.ajax
        ({

            url: "pegaPortifolio.php?id="+idUltimo,
            dataType: "json", //Tipo de Retorno
            success:


  <script>

var corpo = ""; //define a variavel corpo como global


function pegaDados()
{
    var idUltimo = $("#buttonIdUltimoItem").val();
    jQuery.ajax
        ({

            url: "pegaPortifolio.php?id="+idUltimo,
            dataType: "json", //Tipo de Retorno
            success:
            function(data) {
                console.log(data);
                var pt1 = "";
                var i = 1;
                var ultimo_id = 0;

                  var size = 0, key;
                  for (key in data) {
                        if (data.hasOwnProperty(key)) size++; 

                    }

                 for(i = 0; i < size; i++){

                     pt1 +='<div class="element-item '+data[i].menu+'" data-category="transition"><div style="padding:2.5px;"><div style="border: 1px solid #AAAAAA;"><a href="#portfolioModal54" class="portfolio-link" data-toggle="modal"><img src="images/port/mini/'+data[i].imageM+'" alt="project 2"><div class="fundo-port"><h1>"'+data[i].tipo+'"</h1><h2>"'+data[i].nome+'"</h2></div></a></div></div></div>';


                     ultimo_id = data[i].id;
                  }

                  monta_html(pt1);               

            }
        });

}


function monta_html(dados){

  $(".grid").append(dados); //joga o valor para um elemento html
}

</script>

Pegaportifolio.php

 <?php

function fn_conexao(){

    $dbuser = "root";
    $dbpass = "";

    try {

        $pdo = new PDO('mysql:host=localhost;dbname=apixel_galeria',  $dbuser, $dbpass);
        $pdo -> setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
        $pdo->exec("SET CHARACTER SET utf8");//corrige os acentos na hora de gravar no BD
    } catch(Exception $e) {

        echo 'Erro na conexao: ' . $e->getMessage();
    }

    return $pdo;
}

function dados($pdo){

    try {   

            if(!isset($_GET['id']) or $_GET['id'] == null){

                $id = 0; //se o GET nao for enviado o for enviado como nullo , a variável ID pega o valor de 0

            }else{

                $id = $_GET['id']; //pega o valor passado via GET
            }

            $arr = array();

          //aqui , coloquei o limit como 2 para ficar mais facil os testes
            $sql = "SELECT * FROM portfolio WHERE id > $id ORDER BY id DESC LIMIT 3";
            $stmt = $pdo->prepare($sql);
            $stmt->execute();
            $linha = $stmt->fetchAll(PDO::FETCH_ASSOC);

            if($stmt->rowCount() >= 1){

                return $linha; //retorna o resultado da query

            }else {

                return 0;

            }
        } catch(Exception $e) {

            print 'Erro ao inserir os dados no banco: ' . $e->getMessage();
            $conexao = desconecta($conexao);

        }
}

$conexao = fn_conexao();
$dados = dados($conexao);

$dados = json_encode($dados); //converte o resultado para json

print $dados; //imprime os dados na tela
?>
  • Is the JSON return correct or not? It is not possible to test it. Use the console’s "Network" to check the JSON being returned. If you are correct just concentrate with problems in Javascript, if it is not an error in Mysql, or both.

  • I don’t know if you’ve tested it yet, but try calling monta_html() within the for, once he is append will not replace.

  • good friend, from what I see is right... you could me the other way for me to do what I want?

  • @kaiquemix I believe the problem is the line var ultimo_id = 0. Because when you click the button a second time, the whole Ajax routine will repeat itself, so yours ultimo_id will always be 0 after clicking the button. See if I’m right or if I’m only traveling xD.

1 answer

1

This is happening because ajax is storing the cache, so it is normal to always return the same data.

Disable cache on request > cache: false

Stay like this:

function pegaDados()
{
var idUltimo = $("#buttonIdUltimoItem").val();
jQuery.ajax
    ({
        url: "pegaPortifolio.php?id="+idUltimo,
        cache: false, // SEM CACHE
        dataType: "json", //Tipo de Retorno
        success:
        function(data) {
            console.log(data);
            var pt1 = "";
            var i = 1;
            var ultimo_id = 0;

E etc..

Browser other questions tagged

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