Solved

Continual Ajax polling every 3 seconds for ever

Posted on 2013-05-31
10
453 Views
Last Modified: 2013-06-06
I am writing a simple Ajax script to check a MySQL database very 5 seconds for any new records and to add them to a table using jquery.

The page may be open for several hours without reload. The server it will be polling is internal, small, and network has very little traffic so the poll speeds will be instant.

Is their anything I need to be careful of or anything I need to do to keep the 5seconds going?

The system runs a messaging system that isn't operated, so it needs to work and cannot rely on people manually refreshing.

Any guidance would be great!

Steve
0
Comment
Question by:sjtinsley83
  • 5
  • 4
10 Comments
 
LVL 4

Expert Comment

by:Ersoy Hasan
Comment Utility
One of the important things is to be sure the last query has finished or failed before sending the next one. You could use other techniques for this like :
WebSocket
AJAX long polling
AJAX multipart streaming
Forever Iframe
JSONP Polling

there is a library you can use that takes care for choosing the technique http://socket.io/
0
 

Author Comment

by:sjtinsley83
Comment Utility
I've looked into that before but I thought you had to run a difference kind of webserver. We use iis.

Is there a simple example of code you could demonstrate? It's scairs me a bit!

Steve
0
 
LVL 4

Expert Comment

by:Ersoy Hasan
Comment Utility
With .Net you can use SignalR (https://github.com/SignalR). There is a comprehensive documentation, and simple samples.
0
 

Author Comment

by:sjtinsley83
Comment Utility
Oh... I program in PHP. Do I need to look down a different route or will it work with PHP?
0
 
LVL 4

Expert Comment

by:Ersoy Hasan
Comment Utility
well i can't say anything about php, but you can use the first method you said making a request every few seconds:
Be sure that you exclude the time for the connection to complete
Notify the user that you are refreshing the data
Handle errors
Use setTimeout and on every ajax success/error set another one
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 8

Expert Comment

by:soupBoy
Comment Utility
What about using jquery's .promise() method?

Then with a little shift in thinking, instead of having your script run every 5 seconds, you could have it run after every 'completed promise que' (don't know what else to call it) but with a 5 second delay....

Hopefully that made sense!
0
 

Author Comment

by:sjtinsley83
Comment Utility
Thanks for the help guys. I wonder if you would mind looking at my basic code and recommending any improvements:

function getResults(lastUpdated,questionGroupID) {
	
	$.get('library/process.php?action=checkNewQuestionResponses&questionGroupID=' + questionGroupID + '&lastUpdated=' + lastUpdated, function(data) {	// fetch the json data from the php script.

	var resultSet = jQuery.parseJSON(data);	// parse the json.
	var newlastUpdated = lastUpdated; // update last update variable

		for(var ele in resultSet) {   // loop over each row.
	
			if (resultSet[ele].questionResponseDelete == "1" || resultSet[ele].questionResponseToModerator == "0") {
				removeRow(resultSet[ele]);
			}
			
			else if (resultSet[ele].questionResponseName !== "0") {
				addRow(resultSet[ele]);  // add it in to html.
				if(newlastUpdated == lastUpdated) {
				} 	
			}
			
			var timestamp = (resultSet[ele].timestamp.replace(/[":"]/g, ""));
			var timestamp = timestamp.replace(/[-]/g, "");
			var timestamp = timestamp.replace(/[" "]/g, "");

			if( timestamp > newlastUpdated ) {
				newlastUpdated = timestamp;
			}
		}
	setTimeout("getResults(" + newlastUpdated + ","+questionGroupID+");", 5000);
	});         
}

Open in new window

0
 
LVL 4

Assisted Solution

by:Ersoy Hasan
Ersoy Hasan earned 500 total points
Comment Utility
function getResults(lastUpdated,questionGroupID) {
	
	$.get('library/process.php?action=checkNewQuestionResponses&questionGroupID=' + questionGroupID + '&lastUpdated=' + lastUpdated, function(data) {	// fetch the json data from the php script.

	var resultSet = jQuery.parseJSON(data);	// parse the json.
	var newlastUpdated = lastUpdated; // update last update variable

		for(var ele in resultSet) {   // loop over each row.
	
			if (resultSet[ele].questionResponseDelete == "1" || resultSet[ele].questionResponseToModerator == "0") {
				removeRow(resultSet[ele]);
			}
			
			else if (resultSet[ele].questionResponseName !== "0") {
				addRow(resultSet[ele]);  // add it in to html.
				if(newlastUpdated == lastUpdated) {
				} 	
			}
			
			var timestamp = (resultSet[ele].timestamp.replace(/[":"]/g, ""));
			var timestamp = timestamp.replace(/[-]/g, "");
			var timestamp = timestamp.replace(/[" "]/g, "");

			if( timestamp > newlastUpdated ) {
				newlastUpdated = timestamp;
			}
		}
	setTimeout(function () {
                      getResults(newlastUpdated, questionGroupID);
         }, 5000);
	});         
}

Open in new window

You can use $.getJSON instead of $.get, which will return you parsed object.
0
 

Author Comment

by:sjtinsley83
Comment Utility
Nice one!! Any other improvements??
0
 
LVL 4

Accepted Solution

by:
Ersoy Hasan earned 500 total points
Comment Utility
function getResults(lastUpdated,questionGroupID) {
	
	$.get('library/process.php?action=checkNewQuestionResponses&questionGroupID=' + questionGroupID + '&lastUpdated=' + lastUpdated, function(data) {	// fetch the json data from the php script.

	var resultSet = jQuery.parseJSON(data);	// parse the json.
	var newlastUpdated = lastUpdated; // update last update variable

		for(var ele in resultSet) {   // loop over each row.
	
			if (resultSet[ele].questionResponseDelete == "1" || resultSet[ele].questionResponseToModerator == "0") {
				removeRow(resultSet[ele]);
			}
			
			else if (resultSet[ele].questionResponseName !== "0") {
				addRow(resultSet[ele]);  // add it in to html.
				if(newlastUpdated == lastUpdated) {
				} 	
			}
			
			var timestamp = (resultSet[ele].timestamp.replace(/[":"]/g, ""));
			var timestamp = timestamp.replace(/[-]/g, "");
			var timestamp = timestamp.replace(/[" "]/g, "");

			if( timestamp > newlastUpdated ) {
				newlastUpdated = timestamp;
			}
		}
	        setTimeout(function () {
                      getResults(newlastUpdated, questionGroupID);
                }, 5000);
	}).fail(function () {
             // handle on error 
             setTimeout(function () {
                      getResults(newlastUpdated, questionGroupID);
             }, 5000);
        });         
}

Open in new window

0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

Requirements JQuery 1.6+ HTML CSS Introduction This article was inspired by an EE question (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28372511.html) on how to make a page show some balloons animate up a page…
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)

744 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

16 Experts available now in Live!

Get 1:1 Help Now