JavaScript - Most Efficient Way To Auto-refresh A Chatbox?
If you go to a Youtube video by Justin Bieber or Rebecca Black, comments are constantly being posted and it seems like the autorefresh for the comments kicks in every half second. I don't plan on having millions of users viewing my page, but still, wouldn't having every user make a [mysql] request to the server every half second really take a toll on the server (especially since I don't plan to ever have the resources that Youtube has)? Facebook also seems to have instantaneous auto-refreshes, be it in comment boxes or their chat interface.
So what would be the best method to implement a near-instantaneous autorefresh system with minimal resource usage? Similar TutorialsI'm replacing the shoutbox on my site. Everything works and looks great. Now I'd like to make it auto refresh. Here's the update function. PHP Code: function updateShoutbox(){ //send the post to shoutbox.php $.ajax({ type: "POST", url: "shoutbox.php", data: "action=update", complete: function(data){ loading.remove(); messageList.html(data.responseText); } }); } And here is what I've tried to add to make it auti refresh, but it doesn't work. PHP Code: setTimeout('updateShoutbox()', 4000); I know very little about js, so any help is appreciated. <HEAD><TITLE>main</TITLE> <meta http-equiv="refresh" content="5;url=http://localhost/php_basic/short_pro/php/main.php"> <!--<script language="JavaScript"> var i=0; function validat() { setTimeout("moretext()",5000); alert("santosh"); } function moretext() { if(i==0) { alert(window.location); window.location.reload(); i++; } else { } } </script>--> </head> <BODY onload="validat();"> i hav written dis code to auto refresh page only once but it is refreshing after every 5 seconds. Earlier i hav wriiten meta tag but it is refreshing page after every 5 seconds & after that i hav wriiten script to auto reffresh page only once but they both r doin the same work,so can u plz help me in solvin my problem Been trying to get this auto refreshed instead of clicking to refresh <center><iframe src="http://orange.citrus3.com:8338/played.html" width=800 height=400 frameborder=0 scrolling=no id="myiframe"></iframe></center><br> <center><b><BIG><body link="#FF0000"><a href="javascript:myiframe.document.location.reload()">Refresh Current Song</a></BIG></b></center> I have some sample ajax code i have been toying around with. I have it updating & working properly, but you have to click a button first. How can I set it so that it automatically reads the contents of the text file on page load, and updates every 1000ms? I was trying Code: onload=setinterval(JavaScript:xmlhttpPost("status.php"),1000) but had not luck Any suggestions? Code below. PHP Code: <? $myFile = "testFile.txt"; $fh = fopen($myFile, 'r'); $theData = fread($fh, 3); fclose($fh); echo $theData; ?> Code: <html> <head> <title>Simple Ajax Example</title> <script language="Javascript"> function xmlhttpPost(strURL) { var xmlHttpReq = false; var self = this; // Mozilla/Safari if (window.XMLHttpRequest) { self.xmlHttpReq = new XMLHttpRequest(); } // IE else if (window.ActiveXObject) { self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); } self.xmlHttpReq.open('POST', strURL, true); self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); self.xmlHttpReq.onreadystatechange = function() { if (self.xmlHttpReq.readyState == 4) { updatepage(self.xmlHttpReq.responseText); } } self.xmlHttpReq.send(getquerystring()); } function getquerystring() { var form = document.forms['f1']; var word = form.word.value; qstr = 'w=' + escape(word); // NOTE: no '?' before querystring return qstr; } function updatepage(str){ document.getElementById("result").innerHTML = str; } </script> </head> <body> <form name="f1"> <p>word: <input name="word" type="text"> <input value="Go" type="button" onclick='JavaScript:xmlhttpPost("status.php")'></p> <div id="result"></div> </form> </body> </html> I'm using meta refresh to refresh my web page. I have a small compose email window that appears via ajax when the user clicks on a name. Is there a way I can disable the screen refresh in my ajax code while they are composing their message? A noob needs some help. I'm using a combination of Yahoo Pipes and rssdisplayer.js to display some snippets from several RSS feeds on a new site I'm building. The trouble I'm having is that (i) the feeds don't update when I refresh the page, I think because a cached version of the page is being loaded, and (ii) I'd like to have the div containing the feeds auto-refresh at a given time interval. I've got a Twitter javascript working that does both these things, but can't work out how to get the rssdisplayer.js working this way. The rssdisplayer code is: Code: google.load("feeds", "1") //Load Google Ajax Feed API (version 1) function rssdisplayer(divid, url, feedlimit, showoptions){ this.showoptions=showoptions || "" //get string of options to show ("date" and/or "description") var feedpointer=new google.feeds.Feed(url) //create new instance of Google Ajax Feed API feedpointer.setNumEntries(feedlimit) //set number of items to display document.write('<div id="'+divid+'">Loading feed...</div>') this.feedcontainer=document.getElementById(divid) var displayer=this feedpointer.load(function(r){displayer.formatoutput(r)}) //call Feed.load() to retrieve and output RSS feed } rssdisplayer.prototype.formatdate=function(datestr){ var itemdate=new Date(datestr) return "<span style='color:gray; font-size: 90%'>"+itemdate.toLocaleString()+"</span>" } rssdisplayer.prototype.formatoutput=function(result){ if (!result.error){ //if RSS feed successfully fetched var thefeeds=result.feed.entries //get all feed entries as a JSON array var rssoutput="<ul>" for (var i=0; i<thefeeds.length; i++){ //loop through entries var itemtitle="<a href=\"" + thefeeds[i].link + "\">" + thefeeds[i].title + "</a>" var itemdate=/date/i.test(this.showoptions)? this.formatdate(thefeeds[i].publishedDate) : "" var itemdescription=/description/i.test(this.showoptions)? "<br />"+thefeeds[i].content : "" rssoutput+="<li>" + itemtitle + " " + itemdate + itemdescription + "</li>" } rssoutput+="</ul>" this.feedcontainer.innerHTML=rssoutput } else //else, output error alert("Error fetching feeds: "+result.error.message) } //USAGE SYNTAX: new rssdisplayer("divid", "rssurl", numberofitems, "displayoptions") //new rssdisplayer("adiv", "http://www.cssdrive.com/index.php/news/rss_2.0/", 5, "date, description") Hello, I am fairly new to Javascript, but so far I have managed to have the page auto scroll when you browse. I was also able to get a button that toggles the start/stop of the scrolling. What I need to happen is when the scrolling reaches the bottom of the screen, I need it to refresh. Is this possible? Thank you in advance!!! I've a web page when a user logs in, it will have a link that shows the "username" and a link for "logout". After the user logs out, the "username" and the "logout" links will change to "login" and "register" links, respectively. The page uses javascript to check a user cookie, if the user cookie exists, it will show the "username" link and the link for "logout". If no user cookie exists, "login" and "register" links will replace the "username" and "logout" links. Here's the problem: When a user who has log in, clicks the "logout" link, a perl script will delete the user cookie, and redirects back to the same page. The page does not show "login" and "register" links AUTOMATICALLY. Both links will appear ONLY after the user MANUALLY Refreshes the page. It appears that I need a system to refresh the page automacally ONLY one time. How can this be done? Guy help me for the solution... how to refresh the markers only every x... below are my full scripts.... Code: <?php define('INCLUDE_CHECK',1); include "dbconnect.php"; ?> <!DOCTYPE html> <html lang="en"> <head> <script type="text/javascript" src="host_entry/js/jquery-1.7.1.min.js"></script> <!-- Google Map JS --> <script src="http://maps.google.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false" type="text/javascript"></script> </head> <div id="map_canvas" style="top:55px;left:13px;"> <!-- Map will display --> <div id="map"> <!-- Fullscreen Loading & Fullscreen Buttons area --> </div> <!-- Fullscreen Loading & Fullscreen Buttons area Ends --> </div><!-- Map Ends display --> <script type="text/javascript"> /**function show_data() { $('#map').load('index.php'); } setInterval('show_data()', 60000); **/ var locations = [ <?php $query="SELECT * from host_entry"; $result=mysql_query($query)or die(mysql_error()); { if ($num=mysql_numrows($result)) { $i=0; while ($i < $num) { $id=mysql_result($result,$i,"id"); //$host_type=mysql_result($result,$i,"host_type"); $host_name=mysql_result($result,$i,"host_name"); $host_server=mysql_result($result,$i,"host_server"); $host_status=mysql_result($result,$i,"host_status"); $host_lapt=mysql_result($result,$i,"host_lapt"); $host_long=mysql_result($result,$i,"host_long"); $host_circuit=mysql_result($result,$i,"host_circuit"); $host_hotline=mysql_result($result,$i,"host_hotline"); if($host_status==0) echo "['<div class=container style=width:400px;><div class=page-header><h4>$host_name</h4></div>', $host_lapt, $host_long],"; $i++; } }else { echo "<h3 align='center'><font color='#ff0000'>No Content Found</font></h3>"; } } ?> ]; // Setup the different icons and shadows var iconURLPrefix = 'host_entry/img/'; var icons = [ iconURLPrefix + 'p_red_alert.png' ] var icons_length = icons.length; var map = new google.maps.Map(document.getElementById('map'), { zoom: -5, center: new google.maps.LatLng(3.1215681, 101.71180140000001), mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false, streetViewControl: false, disableDefaultUI: true, panControl: false, zoomControlOptions: { position: google.maps.ControlPosition.LEFT_BOTTOM } }); var marker; var markers = new Array(); var iconCounter = 0; var infowindow = new google.maps.InfoWindow({ maxWidth: 400, maxHeight: 350, }); // Add the markers and infowindows to the map for (var i = 0; i < locations.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][1], locations[i][2], locations[i][3], locations[i][4], locations[i][5]), map: map, animation: google.maps.Animation.BOUNCE, icon : icons[iconCounter], }); markers.push(marker); google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent( locations[i][0] ); infowindow.open(map, marker); setTimeout(function(){infowindow.close();}, '5000'); } })(marker, i)); iconCounter++; // We only have a limited number of possible icon colors, so we may have to restart the counter if(iconCounter >= icons_length){ iconCounter = 0; } } function AutoCenter() { // Create a new viewpoint bound var bounds = new google.maps.LatLngBounds(); // Go through each... $.each(markers, function (index, marker) { bounds.extend(marker.position); }); // Fit these bounds to the map map.fitBounds(bounds); } AutoCenter(); </script> </body> </html> do i need to apply setInterval on the marker? how to apply it on the marker so it refresh every X second... please help for the solution.... I currently have this on my companies website and it's having a bit of trouble sometimes where it will only work after a refresh. Is it possible to do a refresh of this div and script as soon as the site loads, instead of using the auto refresh. I tried using auto refresh and it works but whatever time interval I put for the auto refresh is the time that the script pops up, so it kind of just makes it worst. Code: <script type="text/javascript"> $(document).ready(function() { $("#twitter").getTwitter({ userName: "lubellrosen", numTweets: 4, loaderText: "Loading Events...", slideIn: true, slideDuration: 750, showHeading: false, headingText: "Latest Tweets", showProfileLink: false, showTimestamp: false }); }); </script> Hey helpful people. I'm looking for a better solution to refreshing a page of mine, which currently single page (no frames) using meta refresh. To convert it something where it (using frames) would either: a. keep trying to refresh untill a var is recieved from the content, or b. present the browser with a button to refresh and a message that loading failed. But honestly i am a noob at javascript, to an extend i dont have much idea where to start on such a project. but learned this is not possible with regular html that is widely supported anyways. i suspect the:.. window.xx.location='url' ..is useful in this regard, but other than that i am blank on where to start. Any help is appresiated. Thanks in advance Jilli I have a web page that loads and Auto scrolls to the end. I need to either auto scroll up, or when it reaches the bottom auto refreshes back to the top. I have had to define a length longer than the document or I get scroll bars and the Iframe won't scroll. Here is the code. [Code] <html> <head> <script type="text/javascript" language="JavaScript" ></script> <title>How to Scroll the Page With JavaScript</title> <meta name="description" content="How to scroll the page automatically using JavaScript." /> <meta name="keywords" content="javascript, page, scroll" /> <script type="text/javascript"> function pageScroll() { window.scrollBy(0,25); scrolldelay = setTimeout('pageScroll()',5000); // scrolls every 1000 milliseconds } </script> </head> <iframe src="file:///D:/PrivateDocs/WorkflowPage/Stinkyxml.htm" name="frame1" scrolling="auto" frameborder="no" style="float:left" height="4500" width="100%"> <body onLoad="pageScroll()"></body> </iframe> <body> <body onLoad="pageScroll()"></body> </body> </html> [icode] Most of the Javascript I see has some sort of time limit on page reload and is not really what I am trying to accomplish: Code: <meta http-equiv="Refresh" content="10; URL=http://coffeeandtealtd.com/buynow.html" /> I am trying to make our buy page reload after clicking the Paypal "continue shopping" button in Paypal Website Standards. The pop up Paypal shopping cart window closes after clicking the button but our buy page doesn't reload. It doesn't reload in Safari although it seems to be fine in FF and IE. I am new to javascript coding and am not quite sure how to make the page reload in this specific instance only. Any sug's?? I'm attaching my php test file but this is a JS problem. When I scroll down in the web page and the meta refresh hits, in Windows Safari and IE6/7/8 browsers, the web page re-positions back to the top. In Opera and FF the page refreshes but it stays where it is. Can someone look at my test script and see why it is not working in IE and Win Safari? My goal is to have the web page not re-position to the top on the auto refresh. Thanks... I have a php file lets say file1.php, that printing a variable, its dynamic numbers output that already always increasing, like private message numbers that coming or others : PHP Code: <?php echo $variable ?> i want to put that variable output, in another files page title, lets say file2.php or file3.html, in the front of the another files page titles, and auto refresh every x seconds, maybe like this : Quote: (1) - another text in the page title after x seconds, get a private message Quote: (2) - another text in the page title after another x seconds, get another private message Quote: (3) - another text in the page title or its ok if just like this, only the variable, without the another text in the page title Quote: (1) please share your knowledge to make it, maybe using javascript, jquery or others I have asked to create a chatbox, which acts just like a messenger which I type a text in the textbox and press send to show output to the messagebox. However, in my code, I have 2 bugs which is bothering me. The first one is whenever I press spacebar, a "+" sign appear. The second is the first text disappeared whenever I type the second text. Please help me. Code: <html> <head> <title>Untitled</title> <script language="JavaScript" type="text/javascript"> <!-- var isShift=null; var isNN = (navigator.appName.indexOf("Netscape")!=-1); var OP = (navigator.appName.indexOf("Opera")!=-1); if(OP)isNN=true; var key; function shift(event){ key = (isNN) ? event.which : event.keyCode; if (key==16)isShift=1; } function process(event){ key = (isNN) ? event.which : event.keyCode; if(document.layers&&event.modifiers==4){ isShift=1; } if (key==13&&isShift!=1){ document.myForm.submit(); } if (key!=16)isShift=null; } function retrieve(){ document.myForm.text1.focus(); if(location.search.length>0){ blubb=unescape(location.search.split('=')[1]); document.myForm2.text2.value=blubb; } } //--> </script> </head> <body onload="retrieve()"> <form name="myForm"> <textarea name="text1" onkeypress="process(event)" onkeydown="shift(event)" cols="50" rows="7"></textarea><input type="submit" accesskey="s" value="Send"> </form><br><br> This second textarea is just to show, that the line breaks "arrive":<br> <form name="myForm2"> <textarea name="text2" cols="50" rows="7"></textarea> </form> </body> </html> I need help making new messages appearing at the top of the chatbox, not the bottom. Anyone know how to do that? Also, how can I make it hold only X amount of messages then after X amount of messages it just removes the last one. Thanks This isn't all the code but I figure it has to be something within this code that I have to change. If you want to look at the source code to go http://gifts4points.com and take a look there. Code: //Function for initializating the page. function startChat() { //Start Recieving Messages. getChatText(); } //Gets the browser specific XmlHttpRequest Object function getXmlHttpRequestObject() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } else if(window.ActiveXObject) { return new ActiveXObject("Microsoft.XMLHTTP"); } else { document.getElementById('p_status').innerHTML = 'Status: Cound not create XmlHttpRequest Object. Consider upgrading your browser.'; } } //Gets the current messages from the server function getChatText() { if (receiveReq.readyState == 4 || receiveReq.readyState == 0) { receiveReq.open("GET", 'getChat.php?chat=1&last=' + lastMessage, true); receiveReq.onreadystatechange = handleReceiveChat; receiveReq.send(null); } } //Add a message to the chat server. function sendChatText() { if(document.getElementById('txt_message').value == '') { alert("You have not entered a message"); return; } if (sendReq.readyState == 4 || sendReq.readyState == 0) { sendReq.open("POST", 'getChat.php?chat=1&last=' + lastMessage, false); sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); sendReq.onreadystatechange = handleSendChat; var param = 'message=' + document.getElementById('txt_message').value; param += '&name=<?php echo $_SESSION['login']; ?>'; param += '&chat=1'; sendReq.send(param); document.getElementById('txt_message').value = ''; } } //When our message has been sent, update our page. function handleSendChat() { //Clear out the existing timer so we don't have //multiple timer instances running. clearInterval(mTimer); getChatText(); } Hi, I have the below code: Code: <script type="text/javascript"> function loadQuickMessageCheck(File,ID){ var xmlhttp; if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById(ID).innerHTML=xmlhttp.responseText; eucalyptus = setInterval(function(){loadQuickMessageCheck(File,ID)},20000); } } xmlhttp.open("POST",File,true); xmlhttp.send(); } </script> But I am overloading the server and crashing it. I've googled the issue and have found people with similar problems who talk about the need to cancel the last refresh request before they send the next refresh. I even found this nice piece of code which worked for someone else. Quote: try{window.clearTimeout(tRefresh)} catch(err) {} tRefresh = setInterval(setContext, varInterval*60*1000); } I am not sure if this is the solution that I am looking for but if it is all my attempts at applying this code has been a bit of a disaster. Right.. I'm still new to javascript so i've just been messing about with some code and came up with a pointless small program i just wanted to know if the code written is efficient? in other words are there other ways that would be more suitable or are certain parts of the code wrong? The script basically does this. 1. prompts you to enter a time interval in the range of 1 second to 10 seconds 2. A small box appears with a random number generated at the time interval the user entered. IF you enter a number lower or higher then in that range it prompts you again to enter a valid number. If you click cancel you automatically get a time interval of 1 second Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>JavaScript</title> <style type="text/css"> #textbox1{border:1px solid #999;} #fieldsetid{width:157px; border:1px solid #777; font-family:Verdana; margin: 0 auto 0 auto;} </style> <script type="text/javascript"> var count = 0; //Time interval in seconds. do { var getNewValue = prompt("please enter in seconds the interval time", secondTime); var count = getNewValue; if(getNewValue == null){ var count = 1; } if(count > 10){ var secondTime = "please enter a number from 1 to 10"; } } while(count < 1 || count > 10); function makeNumNow() { var MakeNum = Math.random() * 12345678901234567; var result = Math.round(MakeNum); document.form1.textbox1.value = result; } setInterval("makeNumNow()", count*1000); </script> </head> <body> <script type="text/javascript"> </script> <fieldset id="fieldsetid"> <legend>Random Number</legend> <form name="form1"> <input id="textbox1" type="text" name="textbox" value="" /> </form> </fieldset> </body> </html> Right now I am using the following method to show/hide divs containing videos. html Code: <div class="vidPop" id="vidPop"> <div class="vidFrame" id="vidFrame"> <iframe id="Iframe1" src="http://player.vimeo.com/video/xxxxxxx1" width="640" height="360" frameborder="0"></iframe> <div class="vidClose"><a href="#" onclick="vidPopdown()"><img src="images/closeban.png" width="52" height="52" alt="close" /></a></div> </div> </div> <div class="vidPop2" id="vidPop2"> <div class="vidFrame2" id="vidFrame2"> <iframe id="Iframe2" src="http://player.vimeo.com/video/xxxxxxx2" width="640" height="360" frameborder="0"></iframe> <div class="vidClose"><a href="#" onclick="vidPopdown2()"><img src="images/closeban.png" width="52" height="52" alt="close" /></a></div> </div> </div> js Code: function vidPopup() { var o = document.getElementById('vidPop'); o.style.visibility = 'visible'; o = document.getElementById('vidFrame'); o.style.visibility = 'visible'; } function vidPopdown() { var o = document.getElementById('vidPop'); o.style.visibility = 'hidden'; o = document.getElementById('vidFrame'); o.style.visibility = 'hidden'; document.getElementById('Iframe1').src = document.getElementById('Iframe1').src } function vidPopup2() { var o = document.getElementById('vidPop2'); o.style.visibility = 'visible'; o = document.getElementById('vidFrame2'); o.style.visibility = 'visible'; } function vidPopdown2() { var o = document.getElementById('vidPop2'); o.style.visibility = 'hidden'; o = document.getElementById('vidFrame2'); o.style.visibility = 'hidden'; document.getElementById('Iframe2').src = document.getElementById('Iframe2').src } all of this works just fine, but now I am adding yet another video, and I know that this isn't the best way to go about doing this. I ought to be able to use 1 function and tell it which iframe to load, however I dont really know javascript. Any and all help on this would be greatly appreciated. |