Click Here to Go To Your HomePage


Breaking

Friday, 15 September 2017

How to Create a Simple Web-Based Chat Application

In this tutorial we will be creating a simple web-based chat application with PHP and jQuery. This sort of utility would be perfect for a live support system for your website.
If you’re looking for a ready-made app, script, or plugin, you can take a look at one of the many Chat Scripts available on CodeCanyon. Or you could hire an experienced app developer to help you.
Otherwise, learn how to build one yourself in this tutorial.
final product
The chat application we will be building today will be quite simple. It will include a login and logout system, AJAX-style features, and will also offer support for multiple users.
We will start this tutorial by creating our first file called index.php.
  • We start our html with the usual DOCTYPE, html, head, and body tags. In the head tag, we add our title, and link to our css stylesheet (style.css).
  • Inside the body tag, we structure our layout inside the #wrapper div. We will have three main blocks: a simple Menu, our chatbox, and our message input; each with its respective div and id.
    • The #menu div will consist of two paragraph elements. The first will be a welcome to the user and will float left and the second will be an exit link and will float right. We also include a div to clear the elements.
    • The #chatbox div will contain our chatlog. We will load our log from an external file using jQuery's ajax request.
    • The last item in our #wrapper div will be our form, which will include an text input for the user message and a submit button.
  • We add our scripts last to load the page faster. We will first link to the Google jQuery CDN, as we will be using the jQuery library for this tutorial. Our second script tag will be where we will be working on. We will load all of our code after the document is ready.
We will now add some css to make our chat application look better than with the default browser styling. The code below will be added to our style.css file.
There's nothing special about the above css other than the fact that some id's or classes, which we have set a style for, will be added a bit later.
As you can see above, we are finished building the chat's user interface.
Now we will implement a simple form that will ask the user their name before continuing further on.
The loginForm() function we created is composed of a simple login form which asks the user for his/her name. We then use an if and else statement to verify that the person entered a name. If the person entered a name, we set that name as $_SESSION['name']. Since we are using a cookie-based session to store the name, we must call session_start() before anything is outputted to the browser.
One thing that you may want to pay close attention to, is that we have used the htmlspecialchars() function, which converts special characters to HTML entities, therefore protecting the name variable from become victim to Cross-site scripting (XSS). We will later also add this function to the text variable that will be posted to the chat log.
In order to show the login form in case a user has not logged in, and hence has not created a session, we use another if and else statement around the #wrapper div and script tags in our original code. On the opposite case, this will hide the login form, and show the chat box if the user is logged in and has created a session.;
We are not yet finished creating the login system for this chat application. We still need to allow the user to log out, and end the chat session. If you can remember, our original HTML markup included a simple menu. Let's go back and add some PHP code that will give the menu more functionality.
First of all, let's add the users name to the welcome message. We do this by outputting the session of the user's name.
In order to allow the user to log out and end the session, we will jump ahead of ourselves and briefly use jQuery.
The jquery code above simple shows a confirmation alert if a user clicks the #exit link. If the user confirms the exit, therefore deciding to end the session, then we send them to index.php?logout=true. This simple creates a variable called logout with the value of true. We need to catch this variable with PHP:
We now see if a get variable of 'logout' exists using the isset() function. If the variable has been passed via a url, such as the link mentioned above, we proceed to end the session of the user's name.
Before destroying the user's name session with the session_destroy() function, we want to write a simple exit message to the chat log. It will say that the user has left the chat session. We do this by using the fopen(), fwrite(), and fclose() functions to manipulate our log.html file, which as we will see later on, will be created as our chat log. Please note that we have added a class of 'msgln' to the div. We have already defined the css styling for this div.
After doing this, we destroy the session, and redirect the user to the same page where the login form will appear.
After a user submits our form, we want to grab his input and write it to our chat log. In order to do this, we must use jQuery and PHP to work synchronously on the client and server sides.
Almost everything we are going to do with jQuery in order to handle our data, will revolve around the jQuery post request.
  1. Before we do anything, we must grab the user's input, or what he has typed into the #submitmsg input. This can be achieved with the val() function, which gets the value set in a form field. We now store this value into the clientmsg variable.
  2. Here come's our most important part: the jQuery post request. This sends a POST request to the post.php file that we will create in a moment. It posts the clients input, or what has been saved into the clientmsg variable.
  3. Lastly, we clear the #usermsg input by setting the value attribute to blank.
Please not that the code above will go into our script tag, where we placed the jQuery logout code.
At the moment we have POST data being sent to the post.php file each time the user submits the form, and sends a new message. Our goal now is to grab this data, and write it into our chat log.
  1. Before we do anything, we have to start the post.php file with the session_start() function as we will be using the session of the user's name in this file.
  2. Using the isset boolean, we check if the session for 'name' exists before doing anything else.
  3. We now grab the POST data that was being sent to this file by jQuery. We store this data into the $text variable.
  4. This data, as will all overall user input data, will be stored on the log.html file. To do this we open the file with the mode on the fopen function to 'a', which according to php.net opens the file for writing only; places the file pointer at the end of the file. If the file does not exist, attempt to create it. We then write our message to the file using the fwrite() function.
    • The message we will be writing will be enclosed inside the .msgln div. It will contain the date and time generated by the date() function, the session of the user's name, and the text, which is also sorrounded by the htmlspecialchars() function to prevent from XSS.
    Lastly, we close our file handle using fclose().
Everything the user has posted is handled and posted using jQuery; it is written to the chat log with PHP. The only thing left to do is to display the updated chat log to the user.
In order to save ourselves some time, we will preload the chat log into the #chatbox div if it has any content.
We use a similar routine as we used the post.php file, except this time we are only reading and outputting the contents of the file.
The ajax request is the core of everything we are doing. This request not only allows us to send and receive data throught the form without refreshing the page, but it also allows us to handle the data requested.
We wrap our ajax request inside a function. You will see why in a second. As you see above we will only use three of the jQuery ajax request objects.
  • url: A string of the URL to request. We will use our chat log's filename of log.html.
  • cache: This will prevent the our file from being cached. It will ensure that we get an updated chat log everytime we send a request.
  • sucess: This will allow us to attach a function that will pass the data we requested.
As you see, we then move the data we requested (html) into the #chatbox div.
As you may have seen in other chat applications, the content automatically scrolls down if the chat log container (#chatbox) overflows. We are going to implement a simple and similar feature, that will compare the container's scroll height before and after we do the ajax request. If the scroll height is greater after the request, we will use jQuery's animate effect to scroll the #chatbox div.
  • We first store the #chatbox div's scroll height into the oldscrollHeight variable before we make the request.
  • After our request has returned sucessful, we store the #chatbox div's scrolle height into the newscrollHeight variable.
  • We then compare both of the scroll height variables using an if statement. If the newscrollHeight is greater than the oldscrollHeight, we use the animate effect to scroll the #chatbox div.
Now one question may arise, how will we constantly update the new data being sent back and forth between users? Or to rephrase the question, how will we continuously keep sending requests to update the data?
The answer to our question lies in the setInterval function. This function will run our loadLog() function every 2.5 seconds, and the loadLog function will request the updated file and autoscroll the div.
We are finished! I hope that you learned how a basic chat system works, and if you have any suggestions on anything, I'll happily welcome them. This chat system is a simple as you can get with a chat application. You can work off this and build a multiple chat rooms, add an administrative backend, add emoticons, ect. The sky here is your limit.
Also, if you need a professional app or plugin for your next project, you can take a look at one of the many Chat Scripts we have for sale on CodeCanyon
Below are a few links you might want to check if you are thinking of expanding this chat application:

No comments:

Post a Comment

Adbox