Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Building a Chat Application with PHP, JavaScript and Ajax

In this article, we will build a chat application in PHP and AJAX, which will be a real time chat application that is used nowadays in almost all websites for support and maintenance

1. Creating the Index Page

We will start by creating a file called "index.php", which will store the template of the chat application as well as the functionality of the application. In this section, we will only deal with the application template, functionality will be discussed in the later section. So let’s create the file and write the following code in it.

Listing 1. Creating the index page

<!DOCTYPE html>
<html>
    <head>
        <title>My Chat App</title>
        <link rel="stylesheet" href="style.css" media="all" />
    </head>
    
    <body>
        <div id="container">
            <div id="chat_box">
                <div id="chat_data">
                    <span style="color:green;">Samarth: </span>
                    <span style="color:brown;">Hey, How are you?</span>
                    <span style="float:right;">12.30PM</span>
                </div>
            </div>
            
            <form method="post" action="index.php">
                <input type="text" name="name" placeholder="Enter Name: " />
                <textarea name="enter message" placeholder="Enter Message"></textarea>
                <input type="submit" name="submit" value="Send!" />
            </form>
        </div>
    </body>
</html>

To develop other kinds of chats in such other programming languages or platforms, please refer some of our articles:

This is just a simple HTML inside a PHP file with the title "My Chat App". Then we have linked a CSS file which we will create when styling our chat application.

Now, the main template is our chat application. We have created a div called "container", which will contain the whole chat application inside it. We then have another division with the id "chat_box", which will contain only the different chat messages that are being sent and received in real time. We will get the chat data through our database later in this article, but for now we will just enter some dummy data so that our chat application will look good.

We have created three different span tags for displaying the name of sender/receiver, the message and the time when the message was sent or receiver. We have used different styles which are basically different colors for displaying name, message and the time. This is just to make our application look beautiful. This was all about the content that we want inside the division with the id "chat_box". Now we will create a form which will be used by the user to enter his/her name and message and also it will have a button to send the message.

We have created a form which contains three different fields: name of the sender/receiver, message and the send button. We have used an input tag for storing the name because name does not exceed a single line. Then we have a textarea for the message and we have again used an input tag to display the button to send the message to the chat application.

So now it’s time to add some styles to our application to make it more awesome!

Create a file called "style.css" and write the following code inside this file.

Listing 2. Creating the stylesheet for the chat application

 
*{
    padding: 0;
    margin: 0;
    border: 0;
}
 
body{
    background: silver;
}
 
#container{
    width: 40%;
    background: white;
    margin: 0 auto;
    padding: 20px;
}
 
#chat_box{
    width: 90%;
    height: 400px;
}
 
#chat_data{
    width: 100%;
    padding: 5px;
    margin-bottom: 5px;
    border-bottom: 1px solid silver;
    font-weight: bold;
}
 
input[type="text"]{
    width: 100%;
    height: 40px;
    border: 1px solid grey;
    border-radius: 5px;
}
 
input[type="submit"]{
    width: 100%;
    height: 40px;
    border: 1px solid grey;
    border-radius: 5px;
}
 
textarea{
    width: 100%;
    height: 40px;
    border: 1px solid grey;
    border-radius: 5px;
}

This is the code for the CSS for our project. We have used zero padding, margin and border for the whole web page. We have used the background for the body to be silver, which means that our web page will be silver and the chat application background will be white.

After this, we have used custom width and height for the chat application. We have used width in percentages so that our chat application will be responsive. Responsive application means that it will perfectly fit on all types of devices, whether you open it in a mobile browser or in a desktop.

For the form styling we have used the height to be 40 pixels and the width to be 100%. We have used the solid border of color grey and the border radius is 5 pixels. So this was all about styling our chat application. Here is a snapshot of our chat application with a dummy data.

Figure 1. Having a look the chat application.

2. Creating the Database and Table

We will create a database called "chat" and inside this database we will create a table called "chat" and it will have four different columns: ID, Name, Message and Date.

Here is the screenshot of the table that we have to create.

Figure 2. Our Database Table

Now we will insert some dummy data inside this table. Let’s create two new rows inside the table. Here is the snapshot of the data that you have to insert in the chat table.

Figure 3. Filling Dummy Data

Now after saving these two rows in the database, if we browse the table, then we will see that there are two rows present inside the table "chat" which will act as dummy data for us.

Figure 4. Dummy Data inside Database

Now we will create a new file called "db.php" to create a database connection which will make a connection between the database and the PHP file.

Create a file called "db.php" and add the following code to it.

Listing 3. Creating the database

<?php
 
$host = "localhost";
$user = "root";
$pass = "";
$db_name = "chat";
 
$con = new mysqli($host, $user, $pass, $db_name);
 
?>

This is a simple PHP database connection file in which we have created four different variables: host, user, pass and db_name. host will store the value "localhost" as we are not deploying the chat application on the real servers. user and pass will store the username and password for the phpmyadmin. By default, the password is null so we are keeping it blank.

Then we are storing the name of the database "chat" in the variable "db_name".

We are now creating a variable called "con" which will establish a connection between the database and the PHP file. It is a PDO method to establish a database connection. It will take four different arguments, which we have already created earlier in this file.

This is all we have to do in the "db.php" file.

Now we will have to edit the "index.php" file and add some lines of code to it.

Listing 4. Editing the index file

include ‘db.php’;

So now our database connection has been established. To check this, we can refresh the chat application and see whether any error has occurred. If there is no error, it means that our connection has been established.

3. Displaying the Chat data on the page

In this section, we will see how we can display the chat data on the chat application from the database table using query in PHP. Recall that we have earlier created a table for the chat application and we inserted some dummy data inside the table. Now, we will display the same data inside the chat box using queries.

Inside the "index.php" file, recall that we have created a div with the id "chat_box". So inside this div we will add some PHP commands.

Listing 5. Displaying the data

<?php
	$query = "SELECT * FROM chat ORDER BY id";
	$run = $con->query($query);

	while($row = $run->fetch_array()) :
?>

<?php …. ?> is just a simple opening and closing PHP tags. We have created a variable called "query" which will store the MySQL query that we want to run. The query which we have used here means that we will grab all the data from the chat database table and arrange it in ascending order of time which basically means that the recent messages will be displayed at the bottom similar to any chat application that you might have used. We can also arrange the messages in descending order if we want just by adding "DESC" at the end of the query. In that case, our query will end like this "ORDER BY id DESC".

After this we have created a variable "run" which will link the query to the database connection that we created in the "db.php" file in the above section. We have used a while loop in which the condition to stop is whenever the table will be fully traversed. "fetch_array()" means that we are converting the database table row into an array so that we can easily use that in PHP.

Now inside the division with id "chat_data" we will add some more PHP code.

Listing 6. Displaying the data dynamically

<div id="chat_data">
	<span style="color:green;"><?php echo $row['name']; ?> : </span> 
	<span style="color:brown;"><?php echo $row['msg']; ?></span>
	<span style="float:right;"><?php echo $row['date']; ?></span>
</div>
<?php endwhile; ?>

Remember that inside the span tags we had some chat data which we have written. So now we have removed that data and we have inserted some PHP command which will fetch data from the database table of the chat application. Remember that inside the while loop condition we have created an array from the row of the table and now we are using that array to echo name, message and date inside the chat application. This is simply done by the echo statement in PHP. After the end of this div we have created another PHP tag which simply says to end the while loop that we have created above.

So now our chat data is fetched from the database table of the application. Here is a screenshot of the same.

Figure 5. First Look at the application

4. Inserting Chat data into Table

In this section, we will see how we can send the message from the form that we have created into the database table and in return it will be displayed inside the chat application from the table. So inside the "index.php" file after the form tag we will write some PHP code.

Listing 7. Inserting data into database

<?php
	if(isset($_POST['submit'])){
		$name = $_POST['name'];
		$msg = $_POST['enter_message'];

		$query = "INSERT INTO chat (name,msg) VALUES ('$name','$msg')";
		$run = $con->query($query);
	}  
?>

We have created an if statement which checks whether the submit button is pressed on the application. This is done with the help of a function called "isset" in PHP. We are checking whether the "submit" is pressed or not by accessing it from the PHP Super Global which is "$_POST" because the form method is post.

After that we have created two variables for storing the name and message from the form so that we can use a query to store the data in the database table. These values are stored from an array which is a $_POST array in PHP. Now we have created a variable "query" to store the name and message in the table and then we are connecting it with the database using a connection that we have created in the "db.php" file.

So now our chat data can be stored from the form in the database table and we can view it by refreshing the chat application page. Here is a screenshot of the same.

Figure 6. Chat Application working with the form

5. Using AJAX to make it Real Time

In this section, we will see how to use AJAX to make our chat real time, which means that we will not have to refresh the page. Inside the "index.php" file we will add some code in the head tag.

Listing 8. Making an AJAX Request

<script>
	function chat_ajax(){
		var req = new XMLHttpRequest();
		req.onreadystatechange = function() {
			if(req.readyState == 4 && req.status == 200){
				document.getElementById('chat').innerHTML = req.responseText;
			}
		}
		req.open('GET', 'chat.php', true);
		req.send(); 
	}
	
	setInterval(function(){chat_ajax()}, 1000)
</script>

Now we will create a new file called "chat.php" and remove some code from "index.php" and move it into "chat.php".

Listing 9. Some code conversion

<?php
    include 'db.php';
    $query = "SELECT * FROM chat ORDER BY id";
    $run = $con->query($query);
                
    while($row = $run->fetch_array()) :
?>
<div id="chat_data">
    <span style="color:green;"><?php echo $row['name']; ?> : </span> 
    <span style="color:brown;"><?php echo $row['msg']; ?></span>
    <span style="float:right;"><?php echo $row['date']; ?></span>
</div>
<?php endwhile; ?>

So we are using a script tag inside the head tag so that we can make use of AJAX using JavaScript inside the PHP file. We have created a function called "chat_ajax" which will be automatically called whenever our chat application is loaded and it will automatically refresh the page so our chat will become real time.

We have created an HTTP Request object using AJAX. After this we are using an if condition to check whether the page has been successfully loaded. Suppose the page has been loaded and the Request is granted then we will use a JavaScript function "document.getElementById" to get any element by ID on the page and to change its HTML. So then we are changing it to display with the chat data from the database which is written in the "chat.php" file. Remember that chat.php file has the code which was inside the index.php file. We have separated the code so that we can easily understand the AJAX Request.

So now our chat application is complete.

Figure 7. Real Time Chat Application

Conclusion

In this article, we have seen how we can use HTML inside a PHP file and then create a chat application which is capable of real time chatting. We have used a real database to store our chat data and retrieve it inside the chat application. Feel free to start the discussion if you are facing any problem.



CODING is my Passion first, hobby second and job third! I am Full Stack Developer from last two years and I love building scalable web applications and modern websites with new technologies.I started with my web development with ...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login