Show Ajax request progress before completion (redo)

Asked

Viewed 82 times

0

I have the code below, in which I get an ajax query for a file .php. The problem is that this way, I can only return at the end of the process, with the method success:, but I need to inform the user of the processing progress that takes place in PHP. How to proceed? I tried the method beforeSend: but from what the documentation says (and confirmed with a test), it is just a method to do something immediately before sending the request, and nothing else. I need something to interact between the processing on the server and the page on which ajax was launched, that is, for example: in a while {...} inside the .php, I need a way to interact with an internal counter I put there ($counter, for example). Here’s the code:

file . js

$.ajax({
    type:'post',          
    dataType: 'json',
    url: 'genTableBible.php',
    beforeSend: function(dados){
       alert(dados);
    },                            
    success: function(dados){
        for(var i=0;dados.length>i;i++){
            $('#'+xbody).append('<tr class="mudacor"><td class="seleciona" ></td></tr>');
        }
    }
)}

File . php

<?php
    ini_set('memory_limit','-1');
    require_once('CLASSES/usuarios.php');
    $u = new Usuario;
    global $pdo;
    
    $u->conectar("host","mysql.servidor.com.br","user","senha");
    $xmsgErro = $u->msgErro;
    $sql = $pdo->prepare("SELECT * FROM table LIMIT 400");
    $sql->execute();
    $cont = 0;
    while ($result = $sql->fetch(PDO::FETCH_ASSOC))
    {
        $cont++;  // variável para se comunicar com a página/função de origem
        $dados[]=$result;
    }
    echo json_encode($dados);
?>
  • see this link: https://github.hubspot.com/pace/docs/welcome/

1 answer

0


Before your doubt code below should suit you:

$(document).ready(function() {

    /* Configurações de cores da barra */
    var barColor = [
        {"MIN": 0,  "MAX": 30,  "BGCOLOR": "green",  "FONTCOLOR": "white" },
        {"MIN": 31, "MAX": 60,  "BGCOLOR": "yellow", "FONTCOLOR": "black" },
        {"MIN": 60, "MAX": 100, "BGCOLOR": "red",    "FONTCOLOR": "white" }
    ];

    /* Manipula as cores da barra */
    var defineColor = function(v, element) {
        var color = {};
        $.each(barColor, function(k, item){
            if(v >= item.MIN && v <= item.MAX)
                color = item;
        });
        element.style.color = color.FONTCOLOR;
        element.style.backgroundColor = color.BGCOLOR;
    }

    /* Atualizar valor da barra de progresso */
    var updateValue = function(data) {
        if(data){
            data = $.parseJSON(data);
            var bar = document.getElementById("sla-bar");
            var time = data.SLA;
            bar.style.width = time + "px";
            bar.innerHTML = time + "%";
            defineColor(time, bar);

            /* Quando atigir 100 para de rodar a função interval*/
            if(time >= 100)
                clearInterval(interval);
        }
    }

    /* Atualiza a barra de progresso de acordo com resultado PHP (sla.php)*/
    var updateBar = function() {
        $.ajax({
            url: 'sla.php',
            method: 'post',
            type: 'json',
            success: updateValue
        });
    }

    /* Chama a função updateBar() por um intervalo de 2 segundos */
    var interval = setInterval(function(){ updateBar(); }, 2000);
});

Reference: http://blog.rdtecnologia.com.br/php/barra-de-progresso-jquery-ajax-e-php/

  • Lucas Antonio... the answer seems very interesting, because it has link to demo, however, I did not find the php file, nor HTML (the demo did not provide all sources). So, as it is difficult to apply to me at the moment, because adapting the procedures in my app to your example is a little costly (changes the logic almost completely), I will point out your answer as the best by being functional for the reasoning of the proposed problem. Vlw!

  • The php file is in the ajax URL.

  • Okay, I understood better yes, all sources! Lucas Antonio, can you clarify this line on .html: $("#sla-bar"). pb({ url: "sla.php"}); Is that I did not understand the method .pb(...) in Jquery (??) I searched in the Jquery documentation...!

  • Where is this . pb?

  • 1

    hi, sorry for the delay... the . pb is in the html source file, inside the tag <script></script>

  • In your code??

  • no, no link sources html in your reply!

Show 3 more comments

Browser other questions tagged

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