Load from Database only when all is loaded

Asked

Viewed 189 times

-2

In the Portfolio section, when pressing + load, you can see that first loads the block and then the images with a delay of 1 second.

SEE ON SITE: somospixel.com/test

I only want it to load when the images are already loaded.

Function that picks up the data:

    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 filter filtros todos  '+data[i].menu+'" data-category="transition"><div style="padding:2.5px;"><div style="border: 1px solid #AAAAAA;"><a href="#portfolioModal54" onclick="portfolioModal('+data[i].id+')" 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;

                         $("#buttonIdUltimoItem").val(ultimo_id);

                      }

                      monta_html(pt1);               

                }
            });
         filtrar($('#buttonIdUltimoItem').attr('class'));

    }

function monta_html(dados){

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

GRID where the blocks are already loaded:

           <div class="wrap">
<div class="grid">
      <?php
$servidor = 'localhost';
$banco      = '###';
$usuario  = '###';
$senha    = '##';
$link     = @mysql_connect($servidor, $usuario, $senha);
$db          = mysql_select_db($banco,$link);
$idUltimoItem = 0;
if(!$link)
{
    echo "erro ao conectar ao banco de dados!";exit();
}

$sql = "SELECT * FROM portfolio ORDER BY id DESC limit 6";
$query = mysql_query($sql);

while($sql = mysql_fetch_array($query)){
$id = $sql["id"];
$idUltimoItem = $id;
$nome = $sql["nome"];
$tipo = $sql["tipo"];
$desc = $sql["desc"];
$menu = $sql["menu"];
$imageM = "images/port/mini/" . $sql["imageM"];
$imageF = $sql["imageF"];
    ?>
          <div class="element-item filter filtros todos <?php echo "$menu";?>" data-category="transition">

              <div style="padding:2.5px;">
              <div style="border: 1px solid #AAAAAA;">
                   <!--<a href="#portfolioModal54" class="portfolio-link" data-toggle="modal" id="executaAjax" value="Executa ajax">-->
                   <a href="#portfolioModal54" class="portfolio-link" data-toggle="modal" onclick="portfolioModal(<?php echo $id;?>)" value="Executa ajax">
                                            <img src="<?php echo "$imageM"?>" alt="project 2">
                      <div class="fundo-port">
                        <h1><?php echo "$tipo"?></h1>
                        <h2><?php echo "$nome"?></h2>
                    </div>

                      </a>

                  </div>

              </div>

  </div>
        <?php
}
?> 
</div></div>

BUTTON

<div id="rend-more">
         <!-- <input type="hidden" value="0" id="ultimo_id"> campo oculto que armazena o valor do ultimo ID buscado no banco -->

            <button  type="button" id="buttonIdUltimoItem" onClick="pegaDados();" value="<?= $idUltimoItem;?>" style="width: 262px; height: 50px; border: 1px solid rgb(84, 128, 128); position: relative; top: 30%; left: 50%; transform: translateX(-50%); cursor: pointer;  background-color: white;" class="todos">
                <h2 style="text-align: center;color:#4d8984;font-family: 'Gotham-Thin';float: left;font-size: 25px;padding-left: 30px;padding-top: 5px;">CARREGAR</h2>
                <h3 style="padding-left: 5px;float: left;font-size: 25px;color:#4d8984;font-family: 'gotham-bold';padding-top: 5px;">+</h3></button>
        </div> 

Pegar Portfolio:

<?php

function fn_conexao(){

    $dbuser = "####";
    $dbpass = "####";

    try {

        $pdo = new PDO('mysql:host=localhost;dbname=###',  $dbuser, $dbpass);
        $pdo -> setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
    } 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();

            $sql = "ALTER DATABASE portfolio CHARSET = UTF8 COLLATE = utf8_general_ci";
            $sql = "SELECT * FROM portfolio WHERE id < $id ORDER BY id DESC LIMIT 6";
            $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
?>
  • Lazy Load https://css-tricks.com/snippets/javascript/lazy-loading-images/

  • @Lazy I want something like this here aquatro.com, you press to load it takes but load everything already ready

1 answer

1


There are some ways around this,

One of them is to use lazyload that will basically upload the images as needed.

An interesting feature of lazyload that I think you can incorporate to solve your problem is that it exchanges the image for a gif of "loading" in this case you can load your div with the image with "display:None" and leave a space reserved for her and the loading gif in the middle, this will make your layou not break. Then you can check if the image has already loaded using jQuery and checking for example:

$('.seletor').complete

That’ll tell you if you’ve loaded it.

Now the logic of how you’re gonna do it is with you =]

  • got it, it will preload the image, and when it’s called will appear faster right? but it works pulling from the database?

Browser other questions tagged

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