I am trying to make a chat room on my website, I am using php and mysql to store the messages and all the info. How could I automatically refresh the page every time someone updates the database? example:
If I am on my site, the messages show up on my screen but I can only see more recent messages after I refresh the page. Is there a way to make it real-time?
Also I do not know much javascript/ajax/jquery or any of that. Any help is appreciated!
There will be low amount of traffic on my site. Probably around 10-15 people at a time, if that even.
Your best bet is to make an AJAX request every sec or so and see if there are new messages.
You probably do not want to be reloading the page every time. My recommendation, and there are many ways to do this, is to make a ajax call every so often and check/pull the new information from the database.
I would research AJAX and do a tutorial.
This would be accomplished through ajax by calling a function and updating the div. I would not suggest making people refresh a page everytime they send a message it would get ugly. Another option would be using HTML5 web workers
http://msdn.microsoft.com/en-us/hh549259.aspx
You are going to need to learn AJAX in order to make this work well, and jQuery is probably the easiest way to do it. If we can assume that the DIV you want to update has the ID PonyRides, you would want to do:
$("#PonyRides").ajax({url: "/chat.php?getupdates=true"});
This will get the contents of chat.php and stick it into the #PonyRides DIV. This assumes that chat.php will get the contents of the database and format them into HTML.
The remaining challenge is to make it update whenever your database does, but the simplest way is just to reload the whole chat regardless of whether an update has been made or not.
That will impact performance, but if you have less than a hundred chatters you'll probably be fine. If you have more than that, you'd do well to sense inactivity and decrease the checking period, or only send updates instead of the whole chat. Those are more complicated topics, though, and you can build them in as needed once you get these basic concepts down.
To do this, simply wrap the ajax() call in an interval like so:
setInterval(function(){ //the following code runs repeatedly
$("#PonyRides").ajax({url: "/chat.php?getupdates=true"}); //update our chat div
},5000); //repeat every five seconds
The other, awful method would be to load chat in an iFrame, set to reload periodically using the meta refresh technique. This would be dreadful, and can only be recommended if you are trying for some reason to support incredibly old browsers.
You can use AJAX request to update the values
<script type='text/javascript'>
// function for making an object for making AJAX request
function getXMLHTTPRequest() {
try {
req = new XMLHttpRequest();
} catch(err1) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err2) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err3) {
req = false;
}
}
}
return req;
}
var http899 = getXMLHTTPRequest();
function searchFabIndia() {
var myurl = "http://my2nddomain.com/yebhi.php";
myRand = parseInt(Math.random()*999999999999999);
var modurl = myurl+"?rand="+myRand;
http899.open("GET", modurl, true);
http899.onreadystatechange = useHttpResponse899;
http899.send(null);
}
function useHttpResponse899() {
if (http899.readyState == 4) {
if(http899.status == 200) {
// do all processings with the obtained values / response here
// after doing the stuff, call fn again after 30 s say
setTimeout("searchFabIndia()", 30000);
}
}
}
</script>
<body onload='searchFabIndia();'>
I would suggest making an AJAX request to a file on your server which will update the database. If the update to the database is successful then return the message which was updated. Back on the client side you wait for the response and if you get one then append the message to the end of the content. This way you're loading all the messages every time (which would be expensive), you're only loading new messages.
There must be something similar to SignalR(.net) for php. It lets you add code when an event occurs, I think that is what you are looking for.
Related
I'm working on a chatroom type thing where users type in text and hit enter and it gets posted to the main page. I built it with PHP. I have a working model, however to see new posts you have to click the refresh button in the browser. Is there a way to auto refresh this in JavaScript? I'm sure there is, but it seems like if it were to refresh every two seconds than it would be very slow and resource intensive. So is there a work-around? If not well than I guess we could just go with the refresh every few seconds.
I'm now an advanced JavaScript user, so please comment your code and explain what I need to change. Thanks a million!!
Oh, PS, All the comments are saved in a MySQL database and are auto-generated through PHP.
yes, you can do a window refresh every X seconds but as you mentioned there is no need to reload the full page in this scenario. As you said that all the new text comments are in sql, what you can do is using AJAX to call a php function to update them live on screen without a page reload at all.
setTimeout("updateChatAJAx()",2000);
This javascript line will call the "updatechatAJAx" javascript function every 2 seconds.
//Load the message View
function updateChatAJAx(){
var ajaxRequest; // The variable that makes Ajax possible!
ajaxRequest = new XMLHttpRequest();
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//The response
document.getElementById('MoreID').innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "getMessages.php", true);
ajaxRequest.send(null);
}
This above function will be the ajax function which will call the get the output pf your getMessages.php and put the messages into the "MoreID" div element
I'm a newbie, so be kind :)
What is the simplest solution for checking for, retrieving and using newly received data from a mysql database?
The database is being updated from an external api. Ideally I would get it as it arrives but using intervals could work too.
On the first iteration and then once every 5 minutes if there is no new data meanwhile - do an action with the next entry of the array which might cause data to be updated within the next 5 min. But I want to make sure to stop everything if the new data has been received, and just perform some stuff in php.
what's the most simple solution? php vs jquery/ajax?
my proposed solution is in jquery:
<script>
var newdata = false;
if(newdata === false){
setTimeout (function(){
$.each(array, function(){
$.post('checkdb.php',data,function(resp){
if(resp){
newdata=resp;
return newdata;
}
else{
$.post('doaction.php',data);
// cause a potential update within the next 5 min
}
});
});
}, 300000);
}
else{
// move newdata back to php and (then) do something with response
}
</script>
Thanks! :)
My solution in the end is indeed in php and not ajax (there is really no need for client side in this situation).
Here's the outline:
<?php
while (something is true){
//do stuff
flush(); // execute the stuff you did until now
sleep(300); // wait 5 min
// now check database and retrieve new data, if any, and insert into $result
if (isset($result)){
//do stuff with the $result
break; // get out of the loop
}
}
?>
Don't use such logic on client side. JavaScript could be easily manipulated/changed. Someone could replace the interval with much shorter one and stress the server. Read about Comet, use it for waiting for the results from the server. On the server side do all the logic: implement database polling (with interval, as you wish), and, when needed, push the data to the browser/stop polling/do whatever you want.
I have a page on which I want to show a couple of MySQL tables.
There is one table on the right that may only change when a different person is selected.
De second table is the main table in the center. I have a dropdown box with contains every person. The results from the selected person is showed in the middle table. There are multiple results for each person so there is a second dropdown box to choose which of these results you want to show. This is al done by a Ajax XMLHTTP request.
The problem is that the right table uses some javascript. I know this is not possible with Ajax in combination with a XMLHTTP-request. But without the javascript I can't make what I want. Is there a way, to show the right table after the javascript is finished doing his work?
I now use frames. This is not very nice. Because I have to style both pages to look nice together, and that's not so easy as said. But this way it is doing as I want it to be.
So I searched the internet (a long time) and just a few minutes before I wanted to give up i found this piece of code (coming from http://www.javascriptkit.com/dhtmltutors/ajaxincludes.shtml):
function HttpRequest(url){
var pageRequest = false //variable to hold ajax object
/*#cc_on
#if (#_jscript_version >= 5)
try {
pageRequest = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try {
pageRequest = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e2){
pageRequest = false
}
}
#end
#*/
if (!pageRequest && typeof XMLHttpRequest != 'undefined')
pageRequest = new XMLHttpRequest()
if (pageRequest){ //if pageRequest is not false
pageRequest.open('GET', url, false) //get page synchronously
pageRequest.send(null)
embedpage(pageRequest)
}
}
function embedpage(request){
//if viewing page offline or the document was successfully retrieved online (status code=2000)
if (window.location.href.indexOf("http")==-1 || request.status==200)
document.write(request.responseText)
}
}
HttpRequest("external.htm") //include "external.htm" onto current page
This code works perfectly... The first time. As soon as you change the person the whole page disappears and only the table shows up and firefox keeps "loading" the page (you see that circle going round). I do know how to edit the code above to fit my needs but I have no understanding of Ajax or how to fix this problem. Hopefully someone can help me and give me a good solution! And tell me why the code above isn't working properly?
Thanks in advance!
Milaan
document.write only works when the page is loading for the first time, Once the page rendering is done, calling document.write will clear the page first.
https://developer.mozilla.org/en/document.write
What you might want to do instead is:
if (window.location.href.indexOf("http")==-1 || request.status==200) {
var elm = document.createElement('div');
elm.innerHTML = request.responseText;
document.getElementsByTagName('body')[0].appendChild(elm);
}
It´s been a long time since I´ve seen code like this, but one problem I can see, is that you don´t include any kind of variable in your XMLHttpRequest; no user ID or anything. Is it just supposed to load a static page?
And is there any reason you can´t use a library like jQuery? It´s no magic bullet but it will make your life and ajax requests a lot easier.
You might want to use dom functions to add your downloaded content to the existing document, like:
document.getElementById('mypanel').innerHTML = '<html code goes here>';
The best idea probably would be to use a slim javascript framework lie jquery which helps you with browser compatibility.
jQuery should make things easier for you. Your code should look something like this.
$.post("somepage.php", function(data){
$("#divID").html(data);
});
<div id="divID"></div>
And somepage.php could be something like this:
<?php
// get table content
echo "<table>...</table>";
?>
Quite simply, I need to alert the end user when they have a new private message.
From a combination of research and other opinion, I realise I need to use AJAX for this.
The mysql query would be
SELECT id FROM tbl_messages WHERE to_viewed = 1
So when someone sends a message, I want an alert to popup on the screen to inform the user without a page reload.
I have absolutely no idea what I am doing, but know what I want.
Really need help with this, AJAX is definitely something I want to improve as it opens up greater possibilities!
Thanks
Using jQuery for brevity, if you don't have any JavaScript experience I recommend learning.
var check;
function checkForMessages() {
$.get("/newMessages.php", function(data) {
if(data == 1) {
//There are new messages
clearInterval(check);
alert("You have new mail!");
}
});
}
check = setInterval(checkForMessages, 60000);
The above JavaScript will ping the server every 60 seconds. The script "newMessages.php" should return '1' if there are new messages. You have the query already written so I think you can figure it out.
You have two options on the client side:
Polling via Ajax: Every X seconds, send a request to the server to check for messages.
Server-push via Comet: Open a connection to the server and wait for the server to respond with the message.
There are numerous client side libraries available. For Ajax, you can use JQuery. For Comet, look into Dojo, but your server/platform must support Comet. I know it's possible with Java using Jetty, but I'm not sure about other platforms.
I'm using a flash webcam to take a picture. It works great and spits back a URL via POST.
I'm coding in PHP and would like to display this POST data once it is recieved, the problem is that I dont re-load the page.
I've looked around and I'm not sure to dynamically load this array of data.
Where should I be looking? jQuery?
Ah, Figured it out. The Flash thing I have has a built in callback function, so I just have to append the data from there!
jQuery is not able to read any sort of request data other than that which appears in the URL (GET). You will need to use PHP (or some other server-side language) to handle the response created by the FLash application.
Due to the fact that you're using Flash for the process you are at somewhat of a disadvantage because unless the Flash application has some sort of JavaScript "PhotoUploaded" event notification, your page won't be notified that Flash has just submitted a picture to your server which needs to be retrieved and inserted. If you can modify the Flash application to make an external JavaScript event then you can proceed as Frankie has described in his answer; otherwise, if modifying the Flash application is not an option, then another solution would be to have your page send a request to the server every so often (5-10 seconds or so maybe), to check if there is a photo for it to display yet.
The simplest way to setup polling with your server in this fashion would be to make sure that each photo upload from Flash has a unique, pre-determined identifier that your page knows at initial load. You would then simply ping your server every few seconds with an AJAX request and pass it that unique identifier in order to find the right image should one exist.
Basic example:
function GetPhoto() {
$.get('/getphoto.php?ID=1541XJ55A6', function(response) {
if(response.ImageUrl !== "") {
$(".profile-image").attr("src", response.ImageUrl);
if(getPhotoTimer !== undefined) {
clearInterval(getPhotoTimer);
}
}
});
}
$(document).ready(function() {
var getPhotoTimer = setInterval("GetPhoto()", 10000); // every 10 seconds
});
Flash calls javascript each time it spits back the URL.
Javascript contacts server (php) and gets content
Javascript injects content onto page
Like this (flex code):
// attach a function to the completeHandler
private function completeHandler(evt:Event):void {
javascriptComplete();
}
// declare the function that will call the javascript function
private function javascriptComplete():void {
var javascriptFunction:String = "galeryUploadComplete("+Application.application.parameters.opt+")";
ExternalInterface.call(javascriptFunction);
}