Comment section for each thread not loading comments properly - php

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

Related

Chat room refresh in JavaScript

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

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.

PHP and Javascript working together

It may sound odd, but I've been programming games in PHP. The main problem I've found was that the only way to update PHP is to load a page. That makes real-time slow. Javascript can interact with a page without reloading it. Is it possible to load PHP pages on a page using Javascript? So that it would allow PHP to be loaded over and over without reloading.
I've seen it done with Chat rooms but not sure how it works.
We mostly use Ajax, which consists in a client-side Javascript code that calls a server-side page, with out leaving the page.
Here's an example that will get the displayed content of a page, using the GET method (JSFiddle):
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && ((xhr.status>=200 && xhr.status<300) || xhr.status==304)){//Checks if the content was loaded
console.log(this.responseText);
}
}
xhr.open('GET','myPHPPage.php?foo=foo&bar=bar',true);
xhr.send();
And here using the POST method (JSFiddle):
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
var data = 'foo=foo&bar=bar';
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && ((xhr.status>=200 && xhr.status<300) || xhr.status==304)){//Checks if the content was loaded
console.log(this.responseText);
}
}
xhr.open('POST','myPHPPage.php',true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length',data.length);
xhr.send(data);
Note that here we use the setRequestHeader method to change the headers of this HTTP request and, in this case, to change the Content-type and the Content-length (this header has a default value of 4096 bytes). Also, the setRequestHeader method must be called after the open method.
These links should help you:
https://developer.mozilla.org/en/Ajax
http://code.google.com/intl/pt-BR/edu/ajax/tutorials/ajax-tutorial.html
Yes it's incredibly common.
Read up on Ajax.
We call that AJAX!!!
Just Read The documentation on internet about ajax

Ajax ready/notready button without refresh

I am pretty much new to coding but i am learning along the way. i managed to make my buttons in php etcetera but ofcource this refreshes the page which made it very annoying.
I looked around and came to know Ajax. i managed to get certain page parts to auto refresh it's data and i also managed to make a button that changes it's test from Ready / Not Ready and sending data to a php file that processes it and updates the database.
However i am facing with one problem. for example, if a user uses the button sometimes and the database value is set to Ready. if they refresh the page. or close and come back the button would say it's default value Ready while the database already has it set Ready.
The eventual goal is that a user can set his status to ready or not ready for a game match. where the database gets updated so that info can be shown to other users.
I will post my code below, sorry if the code is a mess i can understand it very well might be since i took the pieces from examples on the internet.
var xmlHttp_five = AJAX();
function ajaxFunction(pid) {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlHttp_five) {
var txtname = document.getElementById("txtname");
xmlHttp_five.open("POST","includes/gather_buttons.php",true); //calling testing.php using POST method
xmlHttp_five.onreadystatechange = handleServerResponse;
xmlHttp_five.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp_five.send("txtname=" + txtname.value + "&pid=" + pid); //Posting txtname to PHP File
}
}
function handleServerResponse() {
if (xmlHttp_five.readyState == 4) {
if(xmlHttp_five.status == 200) {
if (document.myForm.button1.value == "Ready") {
document.myForm.button1.value = "Not Ready";
document.myForm.txtname.value = "Waiting";
} else {
document.myForm.button1.value = "Ready";
document.myForm.txtname.value = "Ready";
}
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
and the form below
<form name='myForm'>
<input type='hidden' name='txtname' id='txtname' value='Ready'/>
<input type='button' class='button2' id='button1' value='Ready' onclick='ajaxFunction($pid);' />
</form>
If i need to give more info please say so, sorry if i am not supposed to post this here.
Thank you in advance.
Best regards,
Johan
Your form should be generated by server-side script. So when user refreshes page, he gets actual data from the database.
Otherwise if you can't generate form by server-side script, you should use preloader: button's value initially should be "loading..." and script should request the value by Ajax.

Ajax request with Javascript

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>";
?>

Categories