Solved

ajax reload every 1 second to add new results

Posted on 2010-11-21
14
998 Views
Last Modified: 2012-05-10
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
Comment
Question by:sjtinsley83
  • 6
  • 2
  • 2
  • +4
14 Comments
 

Author Comment

by:sjtinsley83
ID: 34184906
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
 
LVL 6

Expert Comment

by:mickey159
ID: 34185949
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
 
LVL 14

Expert Comment

by:sam2912
ID: 34187489
You will also need a trigger, in your case I suggest:

var intervalObject = setInterval(function, millis);
0
 
LVL 14

Expert Comment

by:sam2912
ID: 34187510
The database should also contain a date/time field, so that you can compare the last update time, to get the new updates.
0
 

Expert Comment

by:tushar-mahajan
ID: 34228995
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
 
LVL 6

Expert Comment

by:mickey159
ID: 34230628
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
 
LVL 2

Expert Comment

by:WilliamStam
ID: 34505752
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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 34615412
0
 
LVL 19

Accepted Solution

by:
Jones911 earned 500 total points
ID: 34940480
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
 

Author Comment

by:sjtinsley83
ID: 34941527
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
 

Author Comment

by:sjtinsley83
ID: 34941533
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
 

Author Comment

by:sjtinsley83
ID: 34942447
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
 

Author Comment

by:sjtinsley83
ID: 34942906
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
 

Author Comment

by:sjtinsley83
ID: 35141086
HI Jones911, Do you have any help to offer from my last post, im still struggling.

Regards

Steve
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Introduction A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer …
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now