Tell me how to use ajax to add a script that will update the information every second on the site without reloading the page.

<div id="content"></div> <script> function show() { $.ajax({ url: "time.php", cache: false, success: function(html){ $("#content").html(html); } }); } $(document).ready(function(){ show(); setInterval('show()',1000); }); </script> 

I tried this script, but there are problems, because it is updated every second the block is flickering

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky
  • @NicolasChabanovsky, only you remembered with this comment - Mr. Black

3 answers 3

What if the server returns an error or the request runs longer than the specified time? Better setTimeout in success or done

 $(document).ready(function() { show(); var count = 0; function show() { $.ajax({ url: 'time.php', cache: false, success: function(data) { count++; $("#content").html(data + ' ' + count); setTimeout(function() {show();}, 1000); } }); } }); 

    What is flickering?

     var counter = 0; function show() { counter++; $("#content").html(counter + " Lorem Ipsum is simply dummy text of the printing and typesetting \ industry. Lorem Ipsum \ has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and \ scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into \ electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of \ Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus \ PageMaker including versions of Lorem Ipsum. " + counter); /*$.ajax({ url: "time.php", cache: false, success: function(html){ $("#content").html(html); } }); */ } $(document).ready(function(){ show(); setInterval(show,1000); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="content"></div> 

    • Like the rules now, hike something else does not work. Thank you - justness

    modern approach - use websocket. update is possible at the initiative of the server there is a data change - the server sends to the client.