Chat room refresh in JavaScript - php

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

Related

Click counter on PHP and MySql

If someone click on clickme div the counter increases in the database. Currently when the page refresh the counter increases.
<div class="Hello">Click Me</div>
<?php
$find_counts = mysqli_query($conn, "SELECT * FROM ad_section");
while($row = mysqli_fetch_assoc($find_counts)){
$current_counts = $row['no_of_clicks'];
$new_count = $current_counts + 1;
$update_count = mysqli_query($conn, "UPDATE `ad_section` SET `no_of_clicks`= $new_count");
}
?>
Alright... so I am going to help you understand what AJAX is in a simplified practical manner.. because once you understand AJAX.. You'll be able to solve this and many other problems.
AJAX is not a 'language' or a 'technology' .. It's just an upgrade to how browsers can interact with servers.
Earlier (before AJAX, long before AJAX), when a browser had to request data/page from the server, it had to either refresh the page or request a whole new page.. and display it on a new window.. but it had absolutely no way of doing so in the "background" .. and then updating the currently displayed HTML page without any disturbance.
This is what AJAX solves.
So now.. through Javascript or Jquery.. (same thing) .. you can send a request to a server (to any end point on any web-server) with data... and the server.. then potentially has the ability to read the data you sent, process it in any way..and return back result in the form of data ..
The data going and coming is in the format of JSON (Javascript Object Notation) ..which is nothing but a way to encode data and arrays
So you send a JSON and the server gives you a back a JSON or an error page (404, etc.. )
The magic happens now...
Your page.. after receiving back the result from the server.. still on the same function execution that had sent the request ... will be able to open up the result.. and using Javascript/Jquery/DOM Manipulation.. plug in the results to the current HTML page or take any new action.. like display an alert, redirect, animate, etc..
So this is how it works:
Imagine you got a DIV upon which a click should set data update on the server and then get result from the server and refresh itself..
<div id='clickme'>People clicked ... <span id='howmany'>1</span></div>
<script>
//Not accurate code, I'm just writing from what I remember .. jquery
$('#clickme').click(function() {
//event captured on click on 'click me'
var nothing = ''; //there is no data to be sent, really.. because we will be getting the update from the server on how many people have clicked it..
//AJAX NOW... //sending a post request
$.post(
'https://mywebsite/index.php/incrementMe',
{data:nothing},
function(data)
{
//this is the function that will receive in its data the result back from the web-server function incrementMe
var result = JSON.parse(data); //parsing the JSON into javascript object/array
$('#howmany').html(result['updatedInfo']); //updatedInfo is the variable within the result that was sent back from the server.. which I then.. using DOM manipulation, plug it back into the span ID
}
);
//End of AJAX request... you didn't have to refresh the page..
</script>
On the server.. you'd have something like this: (writing PHP YII style)
public function actionincrementMe()
{
$data = json_decode($_POST['data']); //got the posted variable and decoded using a PHP function .. to get a PHP array/object
//well in fact, you don't even need this.. because.. there is no info coming to you from the front end .. but if you had, then this is how you'd receive it..
$newnumber = SQL to find out latest number + 1;
print json_encode($newnumber); //this is the function that will just answer back the front-end with a json formated data point..which is the variable new number..which you would then have received in the javascript function.
}
One of the ways is by doing it like this (only the steps i have included)
- Create a table with image id and click counter
- Implement a function on the image click or div click (if there are more images then you can use a generalized image click function
- Inside the function use ajax to implement the count increasing functionality

Comment section for each thread not loading comments properly

I'm building a website where people can leave comments on each event created by me. Each event has its own page eg. showthread.php?t=1, showthread.php?t=2 and so on..
I managed to create a comment section for each event but I got a problem with loading comment for each event. I used $_SESSION['id'] to pass the $_GET['t'] value to another php script
My code is like this:
showthread.php
$id=$_GET['t'];
$_SESSION['id']=$id;
main_function.php
$thread=$_SESSION["id"];
SELECT * FROM comment WHERE thread='$thread' ORDER BY timestamp DESC,
these codes are working fine but I need to refresh the page in order to load the right comment for each thread, is there a way for me to load it properly without refreshing each time I load an event? thanks in advance!
AJAX is javascript used to make requests to the server. You can use it to change your page without refreshing.
Learn more here.
An example of what it looks like:
//create the request object
var xhttp = new XMLHttpRequest();
//activates when you hear back from the server
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//xhttp.responseText is filled with what we get back from the server
document.getElementById("my-element-thing").innerHTML = xhttp.responseText;
}
};
//Type of request, url you're sending to, asyncronous
xhttp.open("GET", "www.google.com?p=myparam", true);
//Send your request to the server
xhttp.send();
Edit: The idea is you would also build a PHP page to accept this request. PHP would analyze it and then echo a response. Be sure that the PHP only contains what you want and nothing else (no tags etc).
Have you tried to use javascript AJAX?
https://www.w3schools.com/xml/ajax_intro.asp

How to refresh a div everytime a database is updated?

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.

ajax and php flag script - set and check for cookie and work with DB

As the title states, I am looking for a flag script, explained below:
It should be like any video site flag script: click the small grey flag once, it becomes colored and you cannot click it again. It should be done in ajax as I don't want my user to have his page reloaded (and all activity restarted) just because he made the mistake of flagging an item on my site.
The php behind should not add multiple flags from the same user - i though it would be a good idea if it checked for a cookie, if not set -> increment field in MySQL and set cookie, if set ->ignore.
This is really urgent, as I am a total noob at ajax and Javascript and I need it done by Tuesday...
The reason I need this is that I really want to know how it's done because a project that we are studying at school has something similar and my homework is to think of a solution that would accomplish the same thing, without looking at the initial source code. I thought of a solution but don't have the time to implement it because this week as well as the next one, I have a ton of exams and I really don't want to miss any...
Thanks in advance for any help you give me!
Cheers!
Make an ajaxrequest, and let that do you php handling, when its done you send the return to your page.
I made you a template. I guess you can do the PHP yourself?
function setFlag(state){
var ajaxRequest; // The variable that makes Ajax possible!
//Set AjaxRequest for all Major browsers, nothing to do here, this is standard
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser is lame!");
return false;
}
}
}
// When the Ajax Request waits for php you get some status codes, everything is done when it reaches 4. Add your javascript events etc here...
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState < 4){
//document.getElementById('ajaxCatchbox').innerHTML = "Load...";
}
if(ajaxRequest.readyState == 4){
// Some Javascript to change your flag colour image
}
}
// this is here your php happens without page reload. (In the php file)
var queryString = "?state=" + state;
ajaxRequest.open("GET", "ThePhpFileThatDoesYourDatabaseHandling.php" + queryString, true);
ajaxRequest.send(null);
}
The PhP does your database and sets the right var on 1 so you'll know which flag is clicked. Every time you refresh the page you use this var to display which flag is clicked. Just when there is no flag clicked yet, you'll add this function and in the Javascript change it on the fly because on that moment you havent reloaded yet.
i added something like state to the function coz I thought you might want to know which flag is clicked but ofc you can add ID our flagnumber etc... and you can send that to php using the querystring...
Gr

How to insert a PHP dropdown in a HTML / Javascript page

Ok, this is my second post, and PLEASE accept that I am a complete newbie, willing to learn, spending many hours trauling various sites for answers, and I've almost got to where I need to be (at least for this bit).
I have a web page which has a nubmer of javascript functions that work together to generate a Google Map with various lines etc. using the google maps API.
I also have a MySQL Database with some information in.
I have created a PHP script to dynamically generate a dropdown box with information from the database. (and that bit seems to work fine) - http://www.bournvilleconservatives.com/temp/select.php
What I now need to do is get that dropdown box to appear in the HTML / Javascript page that I already have, so that when a user selects something from the list, it calls a javascript function with the value selected.
I'm told I need to use AJAX to pull the box in, and use innerhtml to display it, but I really have no idea how, and could do with an example of something similar to help me on my way.
I would put the PHP in the html page, but that page is actually wrapped up in a Joomla! wrapper, so its all rather complicated.
Thanks in advance.
jQuery solution
If you are willing to use jQuery, it will help you a lot with accessing the DOM, making Ajax calls and stuff. Let me give you a solution in jQuery:
First, put a div into HTML (this will store your select box):
<div id="i_want_my_select_here"></div>
Then put this code in the end of you HTML before </body>.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#i_want_my_select_here').load('/temp/select.php');
});
</script>
In the first script tag, we include the jQuery library from Google's CDN. In the second, we write our Javascript/jQuery code. The .load() function makes it easy to make an Ajax call and load the response into an HTML element.
You can see this is much easier than all that code in my other answer :).
If you're using prototype, you can use either Ajax.Request or Ajax.Updater, tho you should have a parent div with either to replace/insert into.
Example w/ Request:
new Ajax.Request('select.php', {
method: 'post',
onSuccess: function(r) {
var select = r.responseText;
$('parent_div').update(select);
}
});
Example w/ Updater:
new Ajax.Request('parent_div', 'select.php', { method: 'post' });
First, the Ajax example (taken from tizag.com and modified), Javascript code comes:
var ajaxRequest; // The variable that we will put an XMLHTTPRequest object in
//We try to create an XMLHTTPRequest object,
//it is the object that lets us use Ajax
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
// and do stuff with it (this function will only run,
// when the data arrives back from the server!)
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){ //if request is successful
//HERE COMES THE DOM INSERTION
}
}
//We call the PHP file
ajaxRequest.open("GET", "/temp/select.php", true);
ajaxRequest.send(null);
What basically happened is that through XMLHTTPRequest we called your PHP file. When the response (PHP file's output) comes, ajaxRequest.onreadystatechange will run instantly. So whatever we want to do with the data received, we have to do it in the place I've written //HERE COMES THE DOM INSERTION.
We want to insert the output into the HTML. To take the easiest route, first create a div/span in your HTML at the exact place you want your select to appear (it's very important to define the ID).
<div id="i_want_my_select_here"></div>
Then again, here comes the Javascript that replaces //HERE COMES THE DOM INSERTION.
//use the id to get Javascript access to the DIV
var div=document.getElementById('i_want_my_select_here');
//put the output of PHP into the div
div.innerHTML=ajaxRequest.responseText;

Categories