0

I have a script in php that displays the content and add another content one in a one second. I want to get this effect in Jquery ajax, unfortunately the text is displayed complete. How to load content on the live in ajax?

My Jquery code:

<div class="div"></div>  
<script src="//code.jquery.com/jquery.js"></script>
<script>
$(document).ready(function(){
  $.ajax({
    url: 'content.php',
    type: 'post',
    data:{ 
      name: 'name' 
    },
    success: function(r){
      $('.div').html(r);
    }
  })
});
</script>

content.php

<?php
echo "one";
ob_end_flush();
flush();
sleep(1);
echo $_POST['name'];
?>
Maistrenko Vitalii
  • 994
  • 1
  • 8
  • 16
URB
  • 3
  • 1

1 Answers1

0

To do exactly what you're asking, you'll need to change your PHP to do echo, flush(), ob_flush(), sleep() and then do something like:

$.ajax('content.php', {
    type: 'post',
    data:{ 
      name: 'name';
    },
    datatype: 'text',
    xhrFields: {
        onprogress: function(e) {
            var cur, response = e.currentTarget.response;
            if(last_len === false) {
                cur = response;
                last_len = response.length;
            } else {
                cur = response.substring(last_len);
                last_len = response.length;
            }
            $('.div').html(cur);
          }
        }
    });

But, using sleep like this is bad practice. Instead, you should handle timing in javascript and make timed ajax requests to different PHP files or with different data to get the desired output. Then, you don't need to do anything fancy just

$.ajax('content.php?first=one', {
    success: function(data) {
         return data; 
    }
});
setTimeout(function() {
    $.ajax('content.php?name=name', {
        success: function(data) {
            return data; 
        }
    });
}, 1000)

which makes two requests to content.php. In your example, the data was static, so I used static parameters. If you needed something dynamic, you could POST the data instead and set posted variables dynamically.

Obviously, to make the second option work, you need to edit content.php accordingly.

Logan Bertram
  • 1,874
  • 1
  • 16
  • 22