We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

How to write a php chat?

AndyPSV
AndyPSV asked
on
Medium Priority
606 Views
Last Modified: 2012-05-07
I'm mainly considered about the reload page issue.
Comment
Watch Question

Unlock this solution with a free trial preview.
(No credit card required)
Get Preview
Chris MichaelidesCEO & Founder
CERTIFIED EXPERT

Commented:
You will need Javascript, even if you don't want to use AJAX calls!

You could have all process being made on a hidden iframe, and from there Javascript can update your elements on the parent document.

This method is not very stable however, and I would strongly suggest that you use AJAX to send your data to php files where you will process all input and output. Once processed, use simple Javascript to update your elements on the page.

A chat application is not a simple script! I've developed a kind of chat commenting system where comments on user activities update live through the internet, so it can be used as a chat application also, since you can chat with other users on the comments section.

You can check it out here http://partypeople.gr  (login: usr=user pwd=activity)

I've attached a Code Snippet from the native Javascript (no libraries loaded) AJAX file here, so you can have a taste of what you need...
The script on http://partypeople.gr uses the jQuery library for the convenience of the display effects and the ease of AJAX calls handling
var xmlhttp;
function loadXMLDoc(url, resp, myid, commentid, commentname, dirname)
{
xmlhttp=null;
if (window.XMLHttpRequest)
  {// code for IE7, Firefox, Opera, etc.
  xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
  xmlhttp.onreadystatechange=
        function ()
            {
            if (xmlhttp.readyState==4)
              {// 4 = "loaded"
              if (xmlhttp.status==200)
                {// 200 = "OK"
 
//==============================================================================
                if (resp=='prepare_comment')
                  {
                var preparedcomment = xmlhttp.responseText;
                var url = dirname+'/components/com_cbactivity/add-on1/helpers/addcomment.php';
  loadXMLDoc(url+'?myid='+myid+'&commentid='+commentid+'&commentname='+encodeURIComponent(preparedcomment), 'save_comment', myid, commentid, preparedcomment, dirname);
                  }
//==============================================================================
                if (resp=='save_comment')
                  {
                          var field = 'mydiv-'+commentid;
                          var button= 'buttondiv-'+commentid;
                          var inputdiv = 'comment-name'+commentid;
                  // process the time display...
                          var currentTime = new Date();
                          var hours = currentTime.getHours();
                          var minutes = currentTime.getMinutes();
                          var suffix = "am";
                          if (hours >= 12) {
                            suffix = "pm";
                            hours = hours - 12;
                          }
                          if (hours == 0) {
                            hours = 12;
                          }
                          if (minutes < 10) minutes = "0" + minutes;
                        
                          var minas = getDateStrWithDOW();
                          
                  // append my comment to the comments div
                          var data = xmlhttp.responseText;
                          var mycommenter = decodeURIComponent(document.getElementById('append-input'+commentid).value);
                          var superaddon_Write = document.getElementById('superaddon_Write').value;
                          now = new Date();
                          now = now.format("isoDateTime");
                          document.getElementById('commentsdiv-'+commentid).innerHTML += "<div class=\"comments_div\" id=\""+data+"\" style=\"display:none;\">"+mycommenter+" <span class=\"activity_infotext\"><span class=\"timeago\" id=\""+now+"\">"+hours+":"+minutes+suffix+" "+minas+"</span></span><br />"+decodeURIComponent(commentname)+"<a style=\"float:right;\" href=\"javascript:delete_comment("+data+")\" title=\"remove this comment\"><img style=\"padding-left:3px;\" src=\""+dirname+"/components/com_cbactivity/add-on1/images/cancel.png\" width=\"10\" /></a></td></tr></table></div>";
                          //$('commentsdiv-'+commentid).htmlText = $('commentsdiv-'+commentid).text;
                          document.getElementById(data).style.display = 'block';
                  // Re-initialize the comment-box for next comment...
                          document.getElementById(field).style.display = 'none';
                          document.getElementById(button).style.display = 'none';
                          document.getElementById(inputdiv).style.fontSize = "10px";
                          document.getElementById(inputdiv).style.color = "#999999";
                          document.getElementById(inputdiv).value = superaddon_Write;
                          document.getElementById(inputdiv).style.display = 'block';
                  }
//==============================================================================
                if (resp=='comment_update')
                  {
                  var data = xmlhttp.responseText;
                  var already = document.getElementById('hidden-div').value;           
                  var appendtocomment = unescape(decodeURIComponent(data));
                  if (already != appendtocomment) {
                    document.getElementById('hidden-div').value = appendtocomment;               
                    var data = appendtocomment.split('-epomeno-');
                    var comment = data[0].split('-sxolia-');
                    var actid = data[1].split(','); 
                    var newtime = data[2];
                    var commentsid = data[3].split(','); 
                    if (newtime!='') {document.getElementById('pageopened').value = newtime;}
                    for(i=0;i<actid.length;i++) {
                        document.getElementById('commentsdiv-'+actid[i]).innerHTML += comment[i]; //alert(commentsid[i]);
                        if (commentsid!='') document.getElementById(commentsid[i]).style.display = 'block';
                    }
                  }
                  setTimeout(commentUpdate, 15000);
                }
//==============================================================================              
                if (resp=='delete_comment')
                  {
                  // Re-initialize the comment-box for next comment...
                          document.getElementById(commentid).style.display = 'none';
                  }
//==============================================================================              
            //      document.getElementById('A1').innerHTML=xmlhttp.status;
              //    document.getElementById('A2').innerHTML=xmlhttp.statusText;
                //  document.getElementById('A3').innerHTML=xmlhttp.responseText;
                }
              else
                {
                alert("Problem retrieving XML data:" + xmlhttp.statusText);// + "|" + resp + "|" + url+'?myid='+myid+'&commentid='+commentid+'&commentname='+preparedcomment+'&dirname='+dirname);
                }
              }
            };
  xmlhttp.open("GET",url,true);
  xmlhttp.send(null);
  }
else
  {
  alert("Your browser does not support XMLHTTP.");
  }
}
 
window.onload = makeDoubleDelegate(window.onload, commentUpdate );
 
	function commentUpdate(){
     var dirname = document.getElementById('dirname').value;
     var url = dirname+'/components/com_cbactivity/add-on1/helpers/commentupdate.php';
 
           var updatedata= document.getElementById('updatedata').value;
           var appendarray= encodeURIComponent(document.getElementById('appendarray').value);
           var pageopened= encodeURIComponent(document.getElementById('pageopened').value);
 
    loadXMLDoc(url+'?updatedata='+updatedata+'&appendarray='+appendarray+'&pageopened='+pageopened, 'comment_update', 0, 0, 0, dirname);
    //myRequest.send('updatedata='+updatedata+'&appendarray='+appendarray+'&pageopened='+pageopened);
  }
// END OF LOADING PAGE FUNCTIONS
// ***************************************************************************************
 
  function get_commentid(id){
      var dirname = document.getElementById('dirname').value;
      var commentid = id;
      var superaddon_Login = document.getElementById('superaddon_Login').value;
      var superaddon_Write = document.getElementById('superaddon_Write').value;
      var url = dirname+'/components/com_cbactivity/add-on1/helpers/preparecomment.php';
      var commentname = encodeURIComponent(document.getElementById('comment-name'+commentid).value);
  
      var field = 'mydiv-'+commentid;
      var button= 'buttondiv-'+commentid;
      var inputdiv = 'comment-name'+commentid;
      var login = 'login'+commentid;
      
  // if not logged in user...
/*      if (commentname != superaddon_Login) {
        $(login).style.display = 'none';
      }*/
      
  // if no comment yet...
      if (commentname=='') {
        var browser=navigator.appName;
        var commentshow = document.getElementById('commentshow-'+commentid).value;
        document.getElementById(field).style.display = 'none';
        document.getElementById(button).style.display = "none"; // let's go for this instead
        document.getElementById(inputdiv).style.fontSize = "10px";
        document.getElementById(inputdiv).style.color = "#999999";
        document.getElementById(inputdiv).value = superaddon_Write;
        //alert (document.activeElement.focus);
        if (commentshow=="block") {
          document.getElementById(inputdiv).style.display = 'block';
          if (browser=="Microsoft Internet Explorer") document.getElementById('commentshow-'+commentid).value = "none";
        } else {
          document.getElementById(inputdiv).style.display = 'none';
          if (browser=="Microsoft Internet Explorer") document.getElementById('commentshow-'+commentid).value = "block";
        }
      } else {
        var pressed = document.getElementById('button-pressed'+commentid).value;
  
  //if button clicked...      
        if (pressed=='PRESSED') {
  
  // prepare elements...
          document.getElementById('button-pressed'+commentid).value = "button-pressed"+commentid;    
  
  // make the AJAX call...
            var myid = document.getElementById('myid').value;
 
          loadXMLDoc(url+'?commentname='+commentname, 'prepare_comment', myid, commentid, commentname, dirname);
          //myRequest.send('myid='+myid+'&commentid='+commentid+'&commentname='+commentname);
 
        }
      }
  }
 
  function showfield(id){
      var browser=navigator.appName;
      var commentid = id;
      var superaddon_Login = document.getElementById('superaddon_Login').value;
      var superaddon_Write = document.getElementById('superaddon_Write').value;
      var commentname = document.getElementById('comment-name'+commentid).value;
      var field = 'mydiv-'+commentid;
      var button= 'buttondiv-'+commentid;
      var inputdiv = 'comment-name'+commentid;
      var login = 'login'+commentid;
      if (document.getElementById(inputdiv).style.display=='none') {
        if (browser=="Microsoft Internet Explorer") document.getElementById('commentshow-'+commentid).value = "block";
        if (commentname != superaddon_Login) {
          document.getElementById(field).style.display = 'block';
          document.getElementById(button).style.display = 'block';
          document.getElementById(inputdiv).style.fontSize = "14px";
          document.getElementById(inputdiv).style.color = "#000000";
          document.getElementById(inputdiv).value = "";
          document.getElementById(inputdiv).style.display = 'block';
          var xx = document.getElementById(inputdiv).focus();
        } else {
          document.getElementById(login).style.display = 'block';
        	setTimeout(function(){get_commentid(commentid)}, 4000);
        }
      } else {
        if (commentname == superaddon_Write) {
          if (browser=="Microsoft Internet Explorer") document.getElementById('commentshow-'+commentid).value = "block";
          document.getElementById(field).style.display = 'block';
          document.getElementById(button).style.display = 'block';
          document.getElementById(inputdiv).style.fontSize = "14px";
          document.getElementById(inputdiv).style.color = "#000000";
          document.getElementById(inputdiv).value = "";
          document.getElementById(inputdiv).style.display = 'block';
          var xx = document.getElementById(inputdiv).focus();
        }
      }
  }
  
  function showmore(id){
      var commentid = id;
      var more = 'more'+commentid;
      var show = 'show'+commentid;
      var hide = 'hidecomments'+commentid;
      document.getElementById(show).style.display = 'none';
      document.getElementById(more).style.display = 'block';
      document.getElementById(hide).style.display = 'block';
  }
  function hidemore(id){
      var commentid = id;
      var more = 'more'+commentid;
      var show = 'show'+commentid;
      var hide = 'hidecomments'+commentid;
      document.getElementById(hide).style.display = 'none';
      document.getElementById(more).style.display = 'none';
      document.getElementById(show).style.display = 'block';
  }
  
  function delete_comment(id){
      var dirname = document.getElementById('dirname').value;
      var commentid = id;
      var url = dirname+'/components/com_cbactivity/add-on1/helpers/deletecomment.php';
          
        loadXMLDoc(url+'?commentid='+commentid, 'delete_comment', 0, commentid, 0, dirname);
        //myRequest.send('commentid='+commentid);
  }
  
  function get_ready(id){
      var commentid = id;
      var field = 'mydiv-'+commentid;
          document.getElementById(field).style.display = 'none';
      var imagediv = 'imagediv-'+commentid;
      var inputdiv = 'button-pressed'+commentid;
      document.getElementById(inputdiv).value = "PRESSED";
      get_commentid(commentid);
  }

Open in new window

gr8gonzoConsultant
CERTIFIED EXPERT

Commented:
The other guys seem to have a handle on this topic, but here's my two cents.

Normally, I don't suggest commercial software, but I've used PHP Live! (version 2.3 - they're up to 3.3 now) in two different projects and it's worked pretty well. It's a good deal for the price - $50 one-time cost for the full source code, so it's potentially cheap enough to save more money in terms of coding time/cost (unless you need to program it from scratch). I wouldn't bother with the add-ons, though. And I promise I don't work for the company or have any ties to them beyond just using their product. :)
gr8gonzoConsultant
CERTIFIED EXPERT

Commented:
Oops. Forgot the URL:
http://www.phplivesupport.com

Author

Commented:
I've bought already this: http://yurivish.com/yshout/
Could anybody paste here the code for jquery which would allow to refresh window?
In general I would however suggest a solution that fits with your requirements, and those can be very different.
If you need to host a chat for many people, with rooms etc and want to have a professional setup, the best is an IRC server. You can then have different programms access this server, Windows, Linux IRC clients and PHP/PERL/JAVA frontends for web users.

On the other hand, if you want to offer chat on your website only for a couple of users, you will always find a huge number of plugins for different CMS packages, standalone solutions to integrate into your website.

I can only support what grvulture said. It is not easy to write that yourself. It's a huge project. If you do not know how to do it and go for it, you should consider it as a learning exercise rather than having the goal to complete it soon. If you want to have a solution in a reasonable time, install something pre-made. There is a lot of it out there for free.
Chris MichaelidesCEO & Founder
CERTIFIED EXPERT

Commented:
The software you bought is already a complete "chat" solution! What do you mean "paste here the code"? The "YShout" application has this already!

I think you are at the beginner level on this, you should really re-consider, and learn how things work first. No offense, friendly advice...
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.