title: how to create user files within a chat and messaging system using ajax and php
body: <p>i really do hope to get a helpful answer. i've been working on a way to make a chatbox that allows private sessions between two users,one where only two users chat with the option of joining the general chatroom, i'm doing this without any xmpp,sockets etc, i'm just using files which would serve as logs, i'll explain the concept:
  a user has logged in, they are directed to the chat-page, where a list of their friends stored in a database is loaded to their right, this part is working fine:</p>
  
  <pre><code>//i've declared all the variables previously
  //skip to the part that loads the names:   
   while($rowb=mysql_fetch_array($done))
  {
  $rafiki=$rowb['name'];
  //show the names,when the user clicks on any of them, the name(variable $jina) of the user
  //and the friend's name are sent to the function makefile()
  echo "&lt;a href='Javascript:makefile(".$jina.",".$rafiki.")'&gt;"."$rafiki"."&lt;/a&gt;"."&lt;br/&gt;";
  }
  </code></pre>
  
  <p>when the user clicks on any name, they are sent to the javascript function, which takes both parameters, the user's name and the name of the friend, and then adds an extension at the end, to make a log file that would serve as the chat log between both of them:</p>
  
  <pre><code>function makefile(username,friendname)
  {
  //add file extension
  var ext=".html";
  //concatenate
  var dash="-";
  var full=username.concat(dash,friendname,dash,ext);
  var str=friendname.concat(dash,username,dash,ext);
  </code></pre>
  
  <p>so each pair would have their own file, the variable full is sent to a script via ajax to make the process seamless, the script does a number of things:
  it first checks to see if a log file, that bears the data sent from the client side exists, either beginning with the user's name or the friend's name,if either file exists,it checks to see if any messages have been sent and writes them to the file, if neither file exists, it creates a new file,and prompts a user that a friend wants to start a chat, when the friend clicks on the user's name, the first condition will succeed, because a file would already have been made:</p>
  
  <pre><code>&lt;?php
  session_start();
  $full=$_POST['full'];
  //first, check to see if variations of the file already exist
  //start by exploding the sent data
  $result=explode("-",$full);
  $usrnme=$result[0];
  $frndnme=$result[1];
  $ext=$result[2];
  //make varied names for comparison
  $vrdfull=array($result[1],$result[0],$result[2]);
  $str=implode("-",$vrdfull);
  $_SESSION['str']=$str;
  $_SESSION['full']=$full;
  //start actual comparison
  if(file_exists($full)||file_exists($str))
  {
  //stuff to do if first file exists
  if(file_exists($full))
  {
  //check to see if message has been sent
  if (isset($_POST['message']))
  {
  $message=$_POST['message'];
  //update existing file with message
  $fp=fopen($full,'a');
  fwrite($fp, "&lt;div id=\"sent\"&gt;".$usrnme." :"." ".$message."&lt;br/&gt;"."&lt;/div&gt;");
  //close the file
  fclose($fp);
  }
  }
  else
  //stuff to do if second file exists
  {if(file_exists($str))
  {
  //check to see if message has been sent
  if (isset($_POST['message']))
  {
  $message=$_POST['message'];
  //update existing file with message
  $fpp=fopen($str,'a');
  fwrite($fpp, "&lt;div id=\"sent\"&gt;".$usrname." :"." ".$message."&lt;br/&gt;"."&lt;/div&gt;");
  //close the file
  fclose($fpp);
  }
  }
  }
  }
  else
  {
  //create file, since neither files exist
  $fhandel=fopen($full,'a');
  //check if message has been sent
  if(isset($_POST['message']))
  {
  $messssage=$_POST['message'];
  fwrite($fhandel,"&lt;div id=\"sent\"&gt;".$usrname." "." : ".$messssage."&lt;br/&gt;"."&lt;/div&gt;");
  }
  fclose($fhandel);
  //send msg to friend, incurring them to accept
  $ext=".html";
  $frrnme=$frndnme.$ext;
  $fpp=fopen($frrnme,'a');
  //prompt the user to initiate chat by opening file,by clicking on the name he/she would see
  fwrite($fpp,"&lt;div id=\"msg\"&gt;".$frndnme." wants to chat, click on their name to accept"."&lt;/div&gt;");
  fclose($fpp);
  }
  ?&gt;
  </code></pre>
  
  <p>i don't think this part has any problems, just posted it to help convey the idea across.here's the ajax that sends the string full to the script (i think it may be wrong):</p>
  
  <pre><code>$.ajax({
  type:'POST',
  url:'makesend.php',
  data: {full:full},
  //what to do if data was sent:
  success: function(full){
  $('#myResponse').html(full);
  
  
  }
  });
  return false;
  </code></pre>
  
  <p>no data is shown in the div "myresponse", so i think there's a problem here, i don't know what. the next thing would be to handle messages sent by the users,here's the form that would get their input:</p>
  
  <pre><code>&lt;form name="message" action=""&gt;
      &lt;input name="message" type="text" id="usermsg" size="63" /&gt;
      &lt;input name="submitmsg" type="submit" onclick="send()"  id="submitmsg" value="Send" /&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>and here's the function send() that sends data to the makesend.php file:</p>
  
  <pre><code>function send(){
  var clientmsg = $("#usermsg").val();
      $.post("makesend.php", {message: clientmsg});               
      $("#usermsg").attr("value", "");
      return false;
  }
  </code></pre>
  
  <p>again, when i tested this and wrote a message, the page reloaded and no data was sent to the script! there's a problem here as well,i don't know what it is. moving on, after the file has been created and the user's begin interaction, it needs to be uploaded to a message area where the user can see it, here's the message area div:</p>
  
  <p>
  remember that i'll need to load a file that exists, so before loading it to this area, i'll need to use php to see which version exists, either one with the user's name first or with the friend's name (either $full or $str):</p>
  
  <pre><code>$("#msgarea").html(
  "&lt;?php
      //check to see if either file exists
  if(file_exists($_SESSION['full'])||file_exists($_SESSION['str'])){
      //check to see if the first file exists:
              if(file_exists($_SESSION['full']))
      {
      $full=$_SESSION['full'];
      $handlle = fopen($full, "r");
      $contents = fread($handlle, filesize($full));
      fclose($handlle);
      //load it's contents to the division if it does
      echo $contents;}
      else
      { 
              //if first file doesn't exist, load the second one:
      $str=$_SESSION['str'];
              //check to see if it exists before loading it
      if(file_exists($str))
      {
      $handle = fopen($str, 'r');
      $contents = fread($handle, filesize($str));
      fclose($handle);
      //load it to the division
      echo $contents;
      }
      }
  }
  ?&gt;"
   );
  </code></pre>
  
  <p>i think it's legal to do that, add php code to the innerHTML of an element, so this code would load whatever version of the file that exists. i get the file names from the session because this part of the code gets executed after data is sent to the makesend.php file, which starts a session and gives them ($_SESSION['full'] and $_SESSION['str']) values. this part that loads the file is the last piece of code within the function makefile(), first, the function obtains data from the user in form of the name they clicked, it sends them to a script (makesend.php) which creates the chat log file, after this, comes the last part, which loads the data onto the division "msgarea". next, i'd need to refresh/reload the created log file after a certain amount of time to show the messages sent by the users, i chose to use 2.5 seconds, this part is outside the function makefile(),i had to use php within the jquery to first check which file exists, i'd then use jquery in the php to reload and animate(auto-scroll) the existing one,this php is inside the 'javascript' tags:</p>
  
  <pre><code> &lt;?php
  //set up the conditions
  
  $full=$_SESSION['full'];
  $str=$_SESSION['str'];
  //check whether either file exists
  if(file_exists($full)||file_exists($str))
  {
   //reload the first file if it exists
  if(file_exists($full)){
  //this is the jquery inside the php(which is also in javascript tags)
  echo '&lt;script type="text/javascript" src="jquery-1.8.0.min (1).js"&gt;&lt;/script&gt;';
  echo '&lt;script type="text/javascript"&gt;';
  echo
  'function loadLog(){        
      var oldscrollHeight = $("#msgarea").attr("scrollHeight") - 20;
      $.ajax({
          url: &lt;?php session_start(); echo $_SESSION[\'full\']?&gt;,
          cache: false,
          success: function(html){        
              $("#msgarea").html(html); //Insert chat log into the #msgarea div               
              var newscrollHeight = $("#msgarea").attr("scrollHeight") - 20;
              if(newscrollHeight &gt; oldscrollHeight){
                  $("#msgarea").animate({ scrollTop: newscrollHeight  }, \'normal\'); //Autoscroll to bottom of div
              }               
          },
      });
  }
  setInterval (loadLog, 2500);    //Reload file every 2.5 seconds';
  }
  else{
      //this will reload the second file since the first doesn't exist:
  echo 
  'function lloadLog(){       
      var oldscrollHeight = $("#msgarea").attr("scrollHeight") - 20;
      $.ajax({
          url: &lt;?php session_start(); echo $_SESSION[\'str\']?&gt;,
          cache: false,
          success: function(html){        
              $("#msgarea").html(html); //Insert chat log into the  #msgarea div              
              var newscrollHeight = $("#msgarea").attr("scrollHeight") -  20;
              if(newscrollHeight &gt; oldscrollHeight){
                  $("#msgarea").animate({ scrollTop: newscrollHeight }, \'normal\'); //Autoscroll to bottom of div
              }               
          },
      });
  }
  setInterval (lloadLog, 2500);   //Reload file every 2.5 secsonds';
  
  }
  echo '&lt;/script&gt;';
  }
  ?&gt;
  </code></pre>
  
  <p>and i think that's it, the entire system, also, there's a problem with the logout call, here's the code, it's at the very end of the file:
       $("#exit").click(function(){
          var exit = confirm("Are you sure you want to end the session?");
          if(exit==true){window.location = 'testing.php?logout=true';}<br>
      });
  here's the markup for it:</p>
  
  <pre><code>&lt;p class="logout"&gt;&lt;a id="exit" href="#"&gt;Exit Chat&lt;/a&gt;&lt;/p&gt;
  </code></pre>
  
  <p>and at the top of the file, here's the part that checks whether it's set to true:</p>
  
  <pre><code>session_start();
  //logout function
  if(isset($_GET['logout']))
  {
  if(file_exists($_SESSION['full'])||file_exists($_SESSION['str']))
  {
  if(file_exists($_SESSION['full']))
  {
  $full=$_SESSION['full'];
  $flogout=fopen($full,'a');
  fwrite($flogout, $_SESSION['username']." has left the anichat!!!  "."&lt;br&gt;");
  fclose($flogout);
  }
  else
  {
  $str=$_SESSION['str'];
  if(file_exists($str))
  {
  $flogoout=fopen($str,'a');
  fwrite($flogoout, $_SESSION['username']." has left the chat  "."&lt;br&gt;");
  fclose($flogoout);
  }
  }
  }
  session_destroy();
  header("Location:testing.php");//user redircect.
  }
  </code></pre>
  
  <p>the user's page is not even refreshed so that the session is destroyed, it just refreshes and the session data is still present(this is because the login form isn't shown, it's supposed to be shown if the $_SESSION['name'] is empty). i know that this is a long question, but i am a beginner and i really need help with this, i think the main issues are with the ajax, but if you can spot anything else i will be very thankful, i kindly ask for a relevant answer that will help me implement this, if you would like me to post the entire code present in both testing.php and makesend.php,in a way that is not separated like the way i've done here to illustrate, please ask if it helps.i thank all you advanced programmers who go out of their way to help others, thanks in advance.</p>