Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How to write a php chat?

Posted on 2009-07-07
7
Medium Priority
?
573 Views
Last Modified: 2012-05-07
I'm mainly considered about the reload page issue.
0
Comment
Question by:AndyPSV
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
  • 2
  • +1
7 Comments
 
LVL 4

Accepted Solution

by:
tokyoahead earned 2000 total points
ID: 24800047
You use Javascript / AJAX. There is no way that you can inform a browser from server side to reload a page only when a chat on the other side has been issued, purely through PHP.
0
 
LVL 2

Expert Comment

by:grvulture
ID: 24800068
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

0
 
LVL 35

Expert Comment

by:gr8gonzo
ID: 24800340
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. :)
0
The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

 
LVL 35

Expert Comment

by:gr8gonzo
ID: 24800344
Oops. Forgot the URL:
http://www.phplivesupport.com
0
 

Author Comment

by:AndyPSV
ID: 24800378
I've bought already this: http://yurivish.com/yshout/
Could anybody paste here the code for jquery which would allow to refresh window?
0
 
LVL 4

Expert Comment

by:tokyoahead
ID: 24800391
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.
0
 
LVL 2

Expert Comment

by:grvulture
ID: 24801727
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...
0

Featured Post

Congratulations! You’re Certified – Now What?

Starting a new career can be overwhelming. Becoming certified in your field of expertise is a great start, but where do you go from here?  Here are some tips to help you on your career journey.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

688 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question