[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1051
  • Last Modified:

ajax reload every 1 second to add new results

I would like to reload a php page every second to show any new results from a mysql database. Ideally I would like the new results to slide in.

Could anyone point me in the right direction of help me on the code.

Many Thanks

Steve Tinsley
0
Steve Tinsley
Asked:
Steve Tinsley
  • 6
  • 2
  • 2
  • +4
1 Solution
 
Steve TinsleyAuthor Commented:
Does anyone have any ideas?? The reload rate doesn't have to be 1 second but I want it looking like it is nearly real time (within 5 / 10 secs).

I'm assuming the way to achieve this is to use Ajax and jquery but I don't really understand it...
0
 
mickey159Commented:
Use $.ajax $.post or $.get.
The reference is below:
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.get/
http://api.jquery.com/jQuery.post/

Use a php page to fetch the data from server,then use another page to make an ajax request.
0
 
sam2912Commented:
You will also need a trigger, in your case I suggest:

var intervalObject = setInterval(function, millis);
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
sam2912Commented:
The database should also contain a date/time field, so that you can compare the last update time, to get the new updates.
0
 
tushar-mahajanCommented:
Hi Steve,

I create a sample code, please have a look.I am using one PHP file to show you the demo.


<!-- demo.php -->
<html>
	<head>
		<script language="javascript" src="jquery-1.4.3.min.js"></script>
		<script language="javascript">
			function callMe() {
				$.get('demo_file.php?'+Math.random() ,function(data) { 
					$("#random").html(data);
				});	
				setTimeout("callMe()",1000);
			}
			callMe();			
		</script>
	</head>
	<body>
		<h2>Random Number</h2>
		<div id="random"></div>
	</body>
</html>

<!-- demo_file.php -->

<?php
	echo rand(1,20000);
?>

Open in new window

0
 
mickey159Commented:
To make the result side in, first put it into a span or div,like the above comment shows.(Something like $("#random").html(data);)
Then use slideDown() to show the data.Maybe like this:
$(".data:last").after("<span class='data'>"+data+"</span>");
$(".data:last").hide();
$(".data:last").slideDown("slow");
0
 
WilliamStamCommented:
look up a thing called long polling. its basicaly where you open a connection.. it stays open till theres a diference on the server.. then brings the data back.. in the success / error parts of your $.ajax (long polling is basicaly $.ajax with a timeout set) you put a setTimeout to call itself again after waiting like 3 seconds or so
0
 
Jones911Commented:
Heres a bit of mock up code that should do what you're asking. I haven't really tested the code or anything since what you ask doesn't really get specific about database structure and whatnot.

The idea is that the PHP code will return a JSON object with all of the row data where each row's auto_increment id is greater than a certain value (In the code, this field is named 'id'). The HTML starts off by calling this php script and getting each row where the id is greater than 0, then a second later it will get all results where the id is greater than the last id it received in the previous fetch. The javascript parses the JSON into an array and then goes through each row it receives and generates HTML for it, appends it to the HTML ad a hidden element and then slides it down.

Whilst this is just conceptual code that probably wont work, but it should give you a pretty good idea on how to get the result you're looking for.

PHP Code
<?php

   // Methods to load up your DB connection
   include("db.php");

   // Get your data.
   $q = mysql_query("SELECT * FROM yourTable WHERE id > {$_GET['lastId']};");

   // Loop through the entire field set and dump all the rows into an array.
   $returnArr = array();
   while($r = mysql_fetch_assoc($q) {
      $returnArr[] = $r;
   }

   // Echo out the array in a JSON string.
   echo json_encode($returnArr);
?>

Open in new window



HTML Code
   <script langauge="javscript" type="text/javascript">
      function getResults(lastId) {

         // fetch the json data from the php script.
         $.get("results.php?lastId=" + lastId, function(data) {

               // parse the json.
               var resultSet = jQuery.parseJSON(data);
               var newLastId = lastId;

               // loop over each row.
               for(var ele in resultSet) {
                  // add it in to html.
                  addRow(resultSet[ele]);

                  if(resultSet[ele][id] > newLastId ) newLastId = resultSet[ele][id]);
               }

               setTimeout("getResults(" + newLastId + ");", 1000);
         });         
      }

      function addRow(rowData) {

         // generate HTML data.
         var htmlData = "<div class='rowData' style='display: hidden;'>";

         // Loop over each field in the data.
         for(var field in rowData) {
            htmlData += field + ": " + rowData[field] + "<br />";
         }

         var htmlData += "</div>";
         
         // Add it to the html, and slide it down.
         $(".rowData:last").after(htmlData);
         $(".rowData:last").slideDown();

      }

      $(document).ready(function(){
          // Kick off the inital result load.
          getResults(0); // replace 0 with where you want to start loading results from.
      });
   </script>

   <body>
      <div class='rowData'></div>
   </body>

Open in new window

0
 
Steve TinsleyAuthor Commented:
That's awesome! I had managed to get something working sort off but not as good as this. I will work on it and let you kn
0
 
Steve TinsleyAuthor Commented:
That's awesome! I had managed to get something working sort of but not as good as this. I will work on it and let you is how I get on!

Thanks

Steve
0
 
Steve TinsleyAuthor Commented:
I have had a play with the code but I have a few errors which I can't work out.

This is the code (newlist.html):
 
<script langauge="javscript" type="text/javascript">
   
      function getResults(lastId) {

         // fetch the json data from the php script.
         $.get('newlist.php?lastId=' + lastId, function(data) {
		 alert("Data Loaded");
		  
               // parse the json.
               var resultSet = jQuery.parseJSON(data);
               var newLastId = lastId;

               // loop over each row.
               for(var ele in resultSet) {
                  // add it in to html.
                  addRow(resultSet[ele]);

                  if( resultSet[ele][id] > newLastId )
		{
		(newLastId = resultSet[ele][id]);
		}
               }

               setTimeout("getResults(" + newLastId + ");", 10000);
         });         
      }
	  
	  
	  

      function addRow(rowData) {

         // generate HTML data.
         var htmlData = "<div class='rowData' style='display: hidden;'>";

         // Loop over each field in the data.
         for(var field in rowData) {
            htmlData += field + ": " + rowData[field] + "<br />";
         }

         htmlData += "</div>";
         
         // Add it to the html, and slide it down.
         $(".rowData:last").after(htmlData);
         $(".rowData:last").slideDown();

      }

	  
	        $(document).ready(function(){
          // Kick off the inital result load.
          getResults(0); // replace 0 with where you want to start loading results from.
      });
 
	  
</script>

<body>
      <div class='rowData'></div>
</body>

Open in new window


When I try and run it in IE I get this error:
Webpage error details
Message: Object expected
Line: 50
Char: 10
Code: 0
URI: http://www.engage-interactive.co.uk/demo/system/manage/newlist.html

Do you have any pointers??

Steve
0
 
Steve TinsleyAuthor Commented:
Scrap that last post, I have managed to get a little further. I hadnt called the jquery library correctly...

My main problem seems to be centering around:
if( resultSet[ele][id] > newLastId )
		{
		(newLastId = resultSet[ele][id]);
		}

Open in new window


id is not defined
[Break On This Error] if( resultSet[ele][id] > newLastId )

In not sure what [id] is?? I assume it is something todo with the database id / array id but I cant work out how to fix this.

0
 
Steve TinsleyAuthor Commented:
HI Jones911, Do you have any help to offer from my last post, im still struggling.

Regards

Steve
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 6
  • 2
  • 2
  • +4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now