How to build group chat system from scratch using html, css, Jquery and php

Over the past few days, I’ve gotten countless number of requests on how to build a web app chat system. So this very article is strictly base on my audience request.

We’re going to work with html and css for the system structure and styling, Jquery for auto page refresh and lastly php for data storing displays information. I believe we already know how.

First, we’ll build the chat system input from where users can type in text. If you are following me up, you already know how to build text input field. So without taking much of your time, let’s start by coding out the chat system input box.

how to create web app chat system from scratch


If we skip the user registration section, the process will be very difficult for some of us to understand properly.

So the first page to start with is the sign up page and its function, secondly, we’ll also create a sign in page. For the sake of this post, we do not need much of user’s information.

Both sign up and sign in pages need only two input fields, a username and password.

Note: if this happens to be that it is your first time and you’ve not done much with writing Jquery and php scripts, then you should go back to my older posts where I teach how to send users information.

 

Create html sign up form from scratch

Sign up form code example;

<form action=”action.php” method=”POST” class=”form-style” >

            <input type=”text” name=”username” required=”required” placeholder=”username” class=”input-style” >

<input type=”text” name=”password” required=”required” placeholder=”password” class=”input-style” >

<input type=”submit” name=”submit” value=”sign up” placeholder=”username” class=”submit-style” >

</form>

This code should be save as sign-up.html

Above html code explanation;

As you can see, I created a sign up html form with two input fields, the first one will hold the “USERNAME” and the second one will holder the user “PASSWORD” and lastly, I also added one submit button that will trigger the action after a visitor finished typing in his/her username and password, then click the button.

Now that we’re done creating our sign up form, it is time we give it a nice look by styling it using the Cascading style sheet. After the styling, then we write the php script that will allow the visitors to send their information into the data.

Remember, we already assigned class attribute to the input fields and even the form element itself.

 

Sign up form style example code;

<style type=”text/css”>

    .input-style

     {

            Width:25%;

            Height:20px;

            Color:black;

            Font-size:15px;

     }

.submit-style

  {

            Width:10%;

            Height:45px;

            Color:white;

            Font-size:25px;

            Border-style:none;

            Background-color:skyblue;

  }

</style>

This code should be save as style-page.css


Related articles:

How to master php valuable and data

How to build php users registration system

How to know the difference between programming and web development

 

Now that we’re done style our sign up form, it is the right time to write the php statement that will enable us to let our visitors sign up.

Remember, our sign up form has only two input fields. So first, we will need to go back to our form code and add “action.php” in the form action attribute. This will trigger the php insert script we’re about writing now.

 

Php insert script code example;

<?php

            $mydb = new mysqli("localhost", "root", "", "netnaija_database");

            if(isset($_SESSION['user_id']))

                                    {

                                                header("Location: index.php");

                                    }

                                   

                                    //Store registration failed and

                                    //already used username and email variables

 

                                    $usernameused = "";

                                    $passwordErr = "";

 

                                               

                                    if(isset($_POST['submit']))

                                    {

                                                if(isset($_POST["password"]))

                                                {

                                                            $password = ($_POST["password"]);

                                                }

                                               

                                                if(isset($_POST["username"]))

                                                {

                                                            $username = ($_POST["username"]);

                                                }

                                               

                                                $mysl = "

                                                SELECT * FROM users_table WHERE  username='{$username}'";

                                                $mysltq = mysqli_query($mydb,$mysl);

                                                $found = mysqli_num_rows($mysltq);

                                               

                                                            if($found)

                                                            {

                                                                        $usernameused = "<br /> Sorry, <b style='color:black;'>{$username}</b> is already taken!";

                                                            }

                                                            else

                                                            {

                                                            $password = $mydb->real_escape_string($password);

                                                            $username = $mydb->real_escape_string($username);

                                                           

                                                            $su = $mydb->prepare("INSERT INTO users_table (password,username) VALUES(?,?)");

                                                            $su->bind_param('ss', $password, $username);

                                                            $su->execute();

                                                           

                                                            if($su)

                                                            {

                                                             header("Location: sign-in.php");

                                                            }

                                                            else

                                                            {          

                                                            $errorreporter = "Sorry, your registration was unsuccessful. Please check properly and retry again. Thank you!";

                                                            }

                                                            }

                                                            }

                                    }

?>

Save this php script as ACTION.PHP

Before we move on, give me a little time to explain what the above php script does. First thing we did is to check if the visitor/user visiting the sign up is already login active person, if it is not, then the visitor can easily sign up, but if he/she is already login, then the script will automatically redirect him to the chat page.

Next we fetched the two values from the form and store them inside php valuables and pas them into the mysqli data.

By now I hope you know all about creating php mysqli data and php valuable, if you can’t still these things, then you should check our previous article on how to create php mysqli data and php valuable to store value.

After we done storing the form input values inside valuables, we check if the username the visitor is trying to use is already registered in the system, if the name is taken, then the person will be notified, but if it is free, the process continues…

Lastly, once the registration is successful, the visitor will be automatically redirected to the sign in page so as the visitor will consider as login active user and can start chatting with other group users.

 

Create html sign in form from scratch

Since we’re done with the sign up page, it is time we create our sign in page. Still, we’re going to create html form with two input fields like that of the sign up form, but this time around, we’re not sending data into our mysqli data but we’ll only compare the values from the two input fields to anyone that matches them before triggering the action.

Remember, this form will have one input field for username and another for password. There must be a third row in your table that should hold users IDs, which is auto increment. We’ll use the individual ID to set a session to indicate when the user is login already.

 

Sign up form code example;

<form action=”login.php” method=”POST” class=”form-style” >

            <input type=”text” name=”username-login” required=”required” placeholder=”enter username” class=”input-style” >

<input type=”text” name=”password-login” required=”required” placeholder=”enter password” class=”input-style” >

<input type=”submit” name=”submit” value=”sign up” placeholder=”username” class=”submit-style” >

</form>

This code should be save as sign-in.html

 

Just like I did with the sign up form, I used same style file I used for the sign up form, so no need of rewriting the entire styling file again.

Now let’s move on to writing our login action file, remember, once a user type in his/her username and password, then click the login button, the script we’re about writing will do the checking job to see if any information matches the one the use type in.

 

Php select script code example;

<?php

            //start session

            session_start();

           

            //database connection

            $mydb = new mysqli("localhost", "root", "", "netnaija_database");

                       

            //Store empty form data variables

            $username = $_POST['username'];

            $user_password = $_POST['password'];

           

            /* Select all in user

            table where the user

            email and password is

            equal to form variables */

            $find = "SELECT * FROM users_table

            WHERE username='{$username}' AND user_password='{$user_password}'";

           

            //Store result variable

            $result = $mydb->query($find);

           

            /* If the result is empty

            redirect to sign in page else

            do what is inside else statement */

            if(!$row = $result->fetch_assoc())

            {

            header("Location: sign-in.php?unsuccess=msg");

            }

            else

            {

            $_SESSION['user_id'] = $row['user_id'];

           

            header("Location: chat.php");

            }

?>

The above script should be save as LOGIN.PHP

I used php if statement to check the table in my data to see if any user has the matches’ information just like the ones typed into the username and password input fields in the sign in form.

If there is no matching information, then the user will get an error message, but if there is a matching data in table, the user will be automatically logged and redirected to the chat page.

 

Create the group chat page from scratch

We’re almost at the final stage. Since users can login to become active users, then it is the right time to create the group chat page.

Note: anyone that is login can drop message in the chat group, there is no restriction.

Again, we’re going to create another form for the very last time, but this time around, the form will have only one input field and a send button. The input field is for the message the user will type. At this point we need to create another table inside our mysqli data and we’ll name this table as CHAT_TABLE.

We’ll make use of the username to show the user that send or drop a message, because we’re going to fetch the username from the USERS_TABLE and automatically insert it inside php valuable, and then send it with the chat message into the CHAT_TABLE. This will enable us to display the username following the message when a particular user dropped in the chat group.

 

Chat group input form code example;

<div class="" style="height:auto;margin-left:90px;">

                                                                        <form action="send-chat.php" method="POST" class="signup-form-class">

                                                                                    <input type="text" name="comment_content" required="required" class="input-field-ele" placeholder="write a comment here!" style="width:auto;height:34px;color:black;border: 2px solid skyblue" />

<input type="submit" name="submiter" value="send" style="width:auto;height:40px;background:skyblue;color:white;border: 2px solid skyblue"/>

                                                                        </form>

                                                            </div>

This page should be save as CHAT.PHP

 

 

We added the style inside the individual html form elements. This styling method is called the “INLINE”. They style will be only apply to these elements in the page.

Since we’re done with chat text box, we can now write the script to send the text and the username into the CHAT_TABLE.

 

Chat message send php script  code example;

session_start();

            //Db connection

            $mydb = new mysqli("localhost", "root", "", "netnaija_database");         

            if(isset($_SESSION['user_id']))

            {

                        $userid = $_SESSION['user_id'];

                        $date = date('Y-m-d');

 

if(isset($_POST['submiter'])){

                        if((empty($_POST['comment_content']))){

                                    $error = "Sorry, you've not type any message!";

                        }else{

                        //Store form data

                        if(isset($_SESSION['user_id']))

                        {

                        $user_id = ($_SESSION['user_id']);

                        $comment = $_POST['comment_content'];

                        $date = date('Y-m-d');

                       

                        /* Select all in user

                        table where the user

                        email and password is

                        equal to form variables */

                                                           

                        //Store result variable

                                                           

                        /* If the result is empty

                        redirect to sign in page else

                        do what is inside else statement */

                        $insert = "INSERT INTO comment_table SET user_id='{$user_id}', post_id='{$id}', comment_content='{$comment}', comment_date='{$date}'";

                        $query = mysqli_query($mydb,$insert);

                                                           

                        }

                        else

                        {

                        $signin = "Sorry, you're not login in, only logged in users can make comment!"; 

                        }

            }

            }

This page should be save as CHAT-SEND.PHP

 

 

Example code explanation;

The above php script is a bit simple you can read. We use unique user ID to fetch the username from the users_table as we earlier stated, and then we assigned it into a valuable and insert it into the chat_table following with the chat message.


Related articles:

How to master php valuable and data

How to build php users registration system

How to know the difference between programming and web development

 

Now users login and drop a message in the chat group. Next is to display the group chat messages so as everyone can see and read what the next person is saying.

Note: we are going to use Jquery to display the messages on the chat group. This is because; we don’t want users to refresh the page before seeing new messages. Jquery will enable us to make our web page auto refresh.

 

 

How to make the chat page auto refresh using jquery

 

What is Jquery? Jquery is a JavaScript library. It was created to make html document much easier. Jquery is a large amount of already written codes; you just need write few lines of commend to trigger the rest of the action codes.

Note: before you start working with Jquery, you must link its file to your web page.

We’re still going to write the Jquery codes inside the group chat page. The purpose of adding the Jquery code, is to make the chat page of automatically reload after few seconds, making it easy for the users to not refresh the page to see new massages.

 

Auto page refresh Jquery  code example;

$(document).ready(function() {

// Auto-refresh this very page on every 2 seconds

setInterval(function() {

 location.reload();

}, 2000);

});

 

Now in every two seconds, the page will refresh itself so as the newest chats will be display. This is where I will stop this article. It is up to you how you’ll make use of this information.

I am leaving with one thing, go search how to download and link Jquery file from the Jquery official website. This should be as a test to you.

See you in my next blog post!

Comments

Popular posts from this blog

How to stop unnecessary service charges from your network providers

Best steps to remove virus from your Computer using command prompt