skip to Main Content

I’m trying to dynamically update text on a PHP page via AJAX. But, instead of the text coming through at different intervals, it all comes at once. Maybe this is the wrong approach.

index.html

<html>
  <head>
    <title>Please Update!</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
     $(function(){
       $.post("hello.php", function(data){
           var success = $("#update");
           success.css("color", "green");
           success.html("> r " + data + ".");
       });
    });
</script>
      
  </head>
  <body>
<div id="update"></div>
  </body>
</html>

hello.php

<?php
    echo "Hello Worldn";
    sleep(1);
    echo "rFoobarn";
    sleep(1);
    echo "rBazboon";
?>

I’d like the text to overwrite itself after one second but it comes barreling down the pipe all at once. ;_;

2

Answers


  1. Not sure about this, but it might help you to do…

    in PHP

    <?php
            $result[] = "Hello Worldn";
            $result[] = "rFoobarn";
            $result[] = "rBazboon";
            print_r($result);
     ?>
    

    in Ajax result

    $.post("hello.php", function(data){
       for(let i = 0; i < data.length; i++) {
          setTimeout(() => {
               // your stuff to do is here by 1 second interval...
               var success = $("#update");
               success.css("color", "green");
               success.html("> r " + data[i] + ".");
          }, 1000*i);
       }
    });
    

    Simple Representation

    var data = ["Hello Worldn","rFoobarn","rBazboon"];
     for(let i = 0; i < data.length; i++) {
        setTimeout(() => {
             console.log(data[i]);
        }, 1000*i);
     }
    Login or Signup to reply.
  2. Like Antony suggested. You could create an array in php and encode it as Json
    and then create a settimeout().

    php

    $data = array("Hello World","Foobar","BazBoo");
    echo json_encode($data);
    
    

    jQuery ~ JavaScript

    
    $.ajax({
        method: "GET",
        url: "hello.php",
        success: (res) => {
            for (let i = 0; i < res.length; i++) {
                setTimeout(() => {
                   // or use .html(res[i])
                    $("#update").text(res[i] + "<br>");
                }, 1000 * i);
    
            }
    
    
        }
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search