Web Chat Application with php, mysql ajax

 Web Chat Application with php, mysql ajax


Query about Chat Application

what is web chat application ?

Ans. Web Chat application is a service software that provides to chat or text message with two or more chat users in the world without any cost but need to wi-fi or internet connection (may be charged include).

 

what's requirement for develop web chat application ?

Ans. There  are two types requirement Hardware and Software.
    1. Hardware:
        a)  Laptop  or Desktop with internet connection
NOTE: you can run this software without internet in localhost server.
    
    2. Software
            a. Xampp or Wampp  Software. (for localhost server)
                                                    or
                real live servers
            b. Web Browser (like mozila).
            c. Code Editor (like notepad)

what use programming  Language for develop web chat application ?

Ans . The following Language use for developing for this  Web Chat Application.

            1. php(for back - end server).

            2. MySQL (for Database ).
            
            3. HTML

            4. CSS

            5. JavaScript

            6. and Ajax.





For Creating Table users and chat:




-- phpMyAdmin SQL Dump
-- version 5.1.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: May 13, 2021 at 09:50 AM
-- Server version: 10.4.18-MariaDB
-- PHP Version: 7.3.28

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `chat`
--

-- --------------------------------------------------------

--
-- Table structure for table `messages`
--

CREATE TABLE `messages` (
  `msg_id` int(11) NOT NULL,
  `incoming_msg_id` int(255) NOT NULL,
  `outgoing_msg_id` int(250) NOT NULL,
  `msg` varchar(1000) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `user_id` int(11) NOT NULL,
  `unique_id` int(200) NOT NULL,
  `fname` varchar(255) NOT NULL,
  `lname` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `img` varchar(400) NOT NULL,
  `status` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `messages`
--
ALTER TABLE `messages`
  ADD PRIMARY KEY (`msg_id`);

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `messages`
--
ALTER TABLE `messages`
  MODIFY `msg_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;



Now Create as new Folder in htdocs "chatapp":

htdocs/chatapp


Now Create new file ("index.php")in htdocs/chatapp:
like -- ../htdocs/chatapp/index.php

and write source code as:



<?php
session_start();
if(isset($_SESSION['unique_id'])){
    header("location: users.php");
}
?>


<?php include_once "header.php"; ?>
<body>

    <div class="wrapper">
        <section class="form signup">
            <header>Realtime Chat App</header>

            <form action="#" enctype="multipart/form-data">

                <div class="error-txt">
                   
                </div>
                <div class="name-details">
                    <div class="field input">
                        <label>First Name</label>
                        <input type="text" name="fname" placeholder="First Name" required>
                    </div>
                    <div class="field input">
                        <label>Last Name</label>
                        <input type="text" name="lname" placeholder="Last Name" required>
                    </div>
                    </div>

                    <div class="field input">
                        <label>Email Address</label>
                        <input type="text" name="email" placeholder="Email Address" required>
                    </div>
                    <div class="field input">
                        <label>Password</label>
                        <input type="password" name="password" placeholder="Password" required>
                        <p>show</p>
                    </div>
                    <div class="field image">
                        <label>Select Image</label>
                        <input type="file" name="image" required>
                    </div>
                    <div class="field button">
                        <input type="submit" value="Continue to chat">
                    </div>
                    <div class="link"> Already signed up? <a href="login.php">Login now</a></div>


                


            </form>
        </section>

    </div>
    <script src="javascript/pass-show-hide.js"></script> 
    
    <script src="javascript/signup.js"></script>   
</body>
</html>



and next create new file as ("login.php") in htdocs/chatapp/login.php
like as /htdocs/chatapp/login.php
write source code as :




<?php
session_start();
if(isset($_SESSION['unique_id'])){
    header("location: users.php");
}
?>
<?php include_once "header.php"; ?>
<body>

    <div class="wrapper">
        <section class="form login">
            <header>Realtime Chat App</header>

            <form action="#">

                <div class="error-txt">
                   
                </div>
                

                    <div class="field input">
                        <label>Email Address</label>
                        <input type="text" name="email" placeholder="Email Address" >
                    </div>
                    <div class="field input">
                        <label>Password</label>
                        <input type="password" name="password" placeholder="Password" >
                        <p>show</p>
                    </div>
                   
                    <div class="field button">
                        <input type="submit" value="Continue to chat">
                    </div>
                    <div class="link"> Not yet signed up? <a href="index.php">Signup now</a></div>


                


            </form>
        </section>

    </div>
    <script src="javascript/pass-show-hide.js"></script> 
    
    <script src="javascript/login.js"></script> 
</body>
</html>



and next create new file as ("style.css") in htdocs/chatapp/login.php
like as /htdocs/chatapp/style.css
write source code as :


*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    text-decoration: none;
    font-family: 'Poppins', sans-serif;

}
body {
    display: flex;
    align-items: center;
    justify-content: center;
    min-width: 100vh;
    background: #f7f7f7;


}
.wrapper {
    background: #fff;
    width: 450px;
    box-shadow: 0 0 128px 0 rgba(0, 0, 0, 0.1), 0 32px 64px -48px rgba(0, 0, 0, 0.5) ;

}

/* Signup Form CSS Code */
.form{
    padding: 25px 30px;
}
.form header{
    font-size: 25px;
    font-weight: 600;
    padding-bottom: 10px;
    border-bottom: 1px solid #e6e6e6;
}

.form form {
    margin: 20px 0;


}
.form form .error-txt{
    color: #721c24;
    background: #f8d7da;
    padding: 8px 10px;
    text-align: center;
    border-radius: 5px;
    margin-bottom: 10px;
    border: 1px solid #f5c6cb;
    display: none;
    

}
.form form .name-details {
    display: flex;
}

form .name-details .field :first-child {
    margin-right: 10px;

}
.form form .field {
    display: flex;
    position: relative;
    flex-direction:column ;
    margin-bottom: 10px;

}
.form form .field label{
    margin-bottom: 2px;

}
.form form .field input{
    outline: none;

}
.form form .input input{
    height: 40px;
    width: 100%;
    font-size: 16px;
    padding: 0 10px;
    border: 1px solid #ccc;
    border-radius: 5px;


}
.form form .image input{

    font-size: 17px;

}
.form form .button input {
    margin-top: 13px;
    height: 45px;
    border: none;
    font-size: 17px;
    font-weight: 400;
    background: #333;
    color: #fff;
    border-radius: 5px;
    cursor: pointer;

}
.form form .field p{
    position: absolute;
    right: 15px;
    color: #ccc;
    top: 70%;
    transform: translateY(-50%);
    cursor: pointer;
}

.form .link {
    text-align: center;
    margin: 10px 0;
    font-size: 17px;

}
.form .link a {
    color: #333;
}
.form .link a:hover{
    text-decoration: underline;
}
/* User area css code */
.users{
    padding: 25px 30px;
}
.users header,
.users-list a{
    display: flex;
    align-items: center;
    padding-bottom:20px ;
    justify-content: space-between;
    border-bottom: 1px solid #e6e6e6;
}
.wrapper img{
    object-fit: cover;
    border-radius: 50%;
}
:is(.users, .users-list) .content{
    display: flex;
    align-items: center;
}

.users header .content img{
    height: 50px;
    width: 50px;

}
:is(.users , .users-list) .details{
    color: #000;
    margin-left:15px ;
}
:is(.users, .users-list) .details span {
    font-size: 18px;
    font-weight: 500;
}
.users header .logout{
    color: #fff;
    font-size: 17px;
    padding: 7px 15px;
    background: #333;
    border-radius: 5px;

}
.users .search{
    margin: 20px, 0;
    display: flex;
    position: relative;
    align-items: center;
    justify-content: space-between;
    


}
.users .search .text{
    font-size: 18px;

}
.users .search input{
    position: absolute;
    height: 42px;
    width: calc(100% - 68px);
    border: 1px solid #ccc;
    padding: 0 13px;
    font-size: 16px;
    border-radius: 5px 0 0 5px;
    outline: none;
    opacity: 0;
    pointer-events: none;
    transition: all 0.3 ease;

}
.users .search input.active{
    opacity: 1;
    pointer-events: auto;

}

.users .search button{
    width: 67;
    height: 42px;
    padding: 3px;
    border: 1px solid #333;
    outline: none;
    color: #333;
    background: #fff;
    cursor: pointer;
    font-size: 17px;
    border-radius: 0 5px 5px 0;
    transition: all 0.2 ease;


}

.users .search button.active{
    color: #fff;
    background: #333;
    width: 67px;
    height: 42px;
    padding: 3px;
    
    text-align: center;
    font-size: 17px;
}
.users .search button.active p::before{
   text-decoration: none;
}


.users-list {
    max-height: 350px;
    overflow-y: auto;

}
:is(.users-list, .chat-box)::-webkit-scrollbar{
    width: 0px;

}
.users-list a {
    margin-bottom: 15px;
    page-break-after:10px ;
    padding-right: 15px;
    border-bottom-color: #f1f1f1;
    

}
.users-list a:last-child{
    border: none;
    margin-bottom: 0px;
}
.users-list a  .content img{
    height: 40px;
    width: 40px;
}


.users-list a .content p{
    color: #67676a;
}
.users-list a  .status-dot {
    font-size: 12px;
    color:#468669 ;
}
/*
we'll use this class name in php to show offline status */

.users-list a .status-dot.offline{
    color: #ccc;
}
 

/* chat Area css code */
.chat-area header{
    display: flex;
    align-items: center;
    padding: 18px 30px;
}
.chat-area header .back-icon {
   color: #333;    

}
.chat-area header img{
    height: 45px;
    width: 45px;


}
.chat-area header span{
    font-size: 17px; 
    font-weight: 500px;  
}
.chat-area header a{
    font-size:33px;
    margin-left: 10px;

    
    }



.chat-box{
    height:500px;
    background:  #f7f7f7;
    padding: 10px 30px 20px 30px;

    box-shadow: inset 0 32px -32px rgb(0 0 0 / 5%), 
                inset 0 -32px 32px rgb(0 0 0 / 5%);
                overflow-y: auto;
}

.chat-box .chat{
    margin: 15px 0;
}
.chat-box .chat p{
    word-wrap: break-word;
    padding: 8px 16px;
    box-shadow: 0 0 32px rgb(0 0 0 / 8%),
    0 16px 16px -16px(0 0 0 / 10%) ;
}

.chat-box .outgoing{
    display: flex;
    align-items: flex-start;
}

.chat-box .outgoing img{
    height: 35px;
    width: 35px;

}
.outgoing .details{
    margin-left: auto;
    max-width: calc(100% - 130px);
}
.outgoing .details p{
    background: #333;
    color: #fff;
    border-radius: 18px 0 18px 18px;
    
}
.chat-box .incoming{
    display: flex;
    align-items: flex-end;


}
.chat-box .incoming img{
    height: 35px;
    width: 35px;

}


.incoming .details{
    margin-left: 10px;
    margin-right: auto;
    max-width: calc(100% - 130px);
}
.incoming .details p{
    background-color: #fff;
    border-radius: 0 18px 18px 18px;
}


.chat-area .typing-area{
    padding: 18px 30px;
    display: flex;
    justify-content: space-between;
}

.typing-area input{
    height: 45px;
    width: calc(100% - 58px);
    font-size: 17px;
    border: 1px solid #ccc;
    border-radius: 5px 0 0 5px;
    padding: 0 13px;
    outline: none;
}
.typing-area button{
    width: 55px;
    border: none;
    outline: none;
    background: #333;
    color: #fff;
    font-size: 30px;
    cursor: pointer;
    border-radius: 0 5px 5px 0;
}



    


and next create new file as ("header.php") in htdocs/chatapp/
like as /htdocs/chatapp/header.php
write source code as :


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Realtime Chat APP</title>

  
    <link rel="stylesheet" href="style.css">
</head>




Warning: Not add close html tag in header.php file




and next create new file as ("users.php") in htdocs/chatapp/
like as /htdocs/chatapp/users.php
write source code as :


<?php  
session_start();
if(!isset($_SESSION['unique_id'])){
header("location: login.php");
}
?>
<?php include_once "header.php"; ?>
<body>

    <div class="wrapper">
        <section class="users">
            <header>
                <?php
                include_once "php/config.php";
                
                $sql = mysqli_query($conn, "SELECT * FROM users WHERE unique_id = {$_SESSION['unique_id']}");
                if(mysqli_num_rows($sql) > 0){
                    $row = mysqli_fetch_assoc($sql);
                }
                ?>
            <div class="content">
                <img src="php/images/<?php echo $row['img']; ?>" alt="">
                <div class="details">
                    <span><?php echo $row['fname'] . " ". $row['lname']; ?></span>
                    <p><?php echo $row['status']?></p>
                </div>

            </div>
            <a href="php/logout.php?logout_id=<?php echo $row['unique_id']; ?>" class="logout">Logout</a>
            </header>
            <div class="search">
                <span class="text">Select an user to start chat</span>
                    <input type="text" name="" placeholder="Enter name to Search ...">
                    <button><p>Search!</p></button>
                </div>


                <div class="users-list">
                   
                </div>
              
        </section>

    </div>
    <script src="javascript/users.js"></script>
    
</body>
</html>










and next create new file as ("chat.php") in htdocs/chatapp/
like as /htdocs/chatapp/chat.php
write source code as :


<?php  
session_start();
if(!isset($_SESSION['unique_id'])){
header("location: login.php");
}
?>

<?php include_once "header.php"; ?>
<body>

    <div class="wrapper">
        <section class="chat-area">
            <header>
            <?php
                include_once "php/config.php";
                $outgoing_id ="";
                $incoming_id ="";
                $message = "";











                $user_id = mysqli_real_escape_string($conn, $_GET['user_id']);
                 
              
                $sql = mysqli_query($conn, "SELECT * FROM users WHERE unique_id = {$user_id}");
                if(mysqli_num_rows($sql) > 0){
                    $row = mysqli_fetch_assoc($sql);
                }

                ?>
                <a href="users.php" class="back-icon">&#x2B05</a>
                <img src="php/images/<?php echo $row['img']; ?>" alt="">
                <div class="details">
                    <span><?php echo $row['fname'] . " ". $row['lname']; ?></span>
                    <p><?php echo $row['status']?></p>
                </div>
            
            </header>

            <div class="chat-box">
                           
            </div>
            <form action="" class="typing-area" autocomplete="off" method="POST">
            <input type="text"  name="outgoing_id" value="<?php echo $_SESSION['unique_id']; ?>" hidden>
            <input type="text" name="incoming_id" value="<?php echo $user_id; ?>" hidden>



                <input type="text" name="message" class="input-field" name="" placeholder="Type here a message here...">
                <button type="submit" name="submited" >➤</button>




            </form>
          
        </section>

    </div>

    <script src="javascript/chat.js"></script>
    
</body>
</html>
<?php

if (isset($_POST["submited"])) {
    $outgoing_id = mysqli_real_escape_string($conn, $_POST['outgoing_id']);
    
    $incoming_id = mysqli_real_escape_string($conn, $_POST['incoming_id']);

    $message = mysqli_real_escape_string($conn, $_POST['message']);
    if (!empty($message)) {
        $sql = mysqli_query($conn, "INSERT INTO messages (incoming_msg_id, outgoing_msg_id, msg) 
VALUES ('{$incoming_id}', '{$outgoing_id}', '{$message}')") or die();
    }
}

?>




Now create new Folder as ("php") in htdocs/chatapp/
like as /htdocs/chatapp/php/


 create new file as ("config.php") in htdocs/chatapp/
like as /htdocs/chatapp/php/config.php
write source code as :


<?php

$conn = mysqli_connect("localhost", "root", "", "chat");
if(!$conn) {
    echo "Database connection fail!" . mysqli_connect_error();

}

?>


Warnning Check localhost or real server conection connect or not: 



 create new file as ("data.php") in htdocs/chatapp/
like as /htdocs/chatapp/php/data.php
write source code as :


<?php
while($row = mysqli_fetch_assoc($sql)) {
    $sql2 = "SELECT * FROM messages WHERE (incoming_msg_id = {$row['unique_id']}
     OR outgoing_msg_id = {$row['unique_id']}) AND (outgoing_msg_id = {$outgoing_id}
     OR incoming_msg_id = {$outgoing_id}) ORDER BY msg_id DESC LIMIT 1 ";
     $query2 = mysqli_query($conn, $sql2);
     $row2 = mysqli_fetch_assoc($query2);
     if(mysqli_num_rows($query2) > 0) {
         $result = $row2['msg'];
     }else {
         $result = "No message available";
     }

     // trimming message if word are more than 28
     (strlen($result) > 28) ? $msg = substr($result, 0, 28).'...' : $msg = $result;
     // adding you : text before msg if login id send msg
     ($outgoing_id == $row2['outgoing_msg_id']) ? $you ="You: " : $you = "";
     // check user is online or offline
     ($row['status'] == "Offline now") ? $offline = "offline" : $offline = "";


        $output .= '
        
                    <a href="chat.php?user_id='.$row['unique_id'].'">
                    <div class="content">
                        <img src="php/images/' .$row['img']. '" alt="">
                        <div class="details">
                            <span>'. $row['fname'] . " ".$row['lname'].'</span>
                            <p>'.$you . $msg.'</p>
                        </div>
                        
                    </div>
                    <div class="status-dot '.$offline.'"><i class="fas fa-circle"></i></div>
                </a> ';
    }
    ?>





 create new file as ("get-chat.php") in htdocs/chatapp/
like as /htdocs/chatapp/php/get-chat.php
write source code as :



<?php
    session_start();
    include_once "config.php";
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $password = mysqli_real_escape_string($conn, $_POST['password']);
    if (!empty($email) && !empty($password)) {
        // let's check user entered email & password matched to databse any table row email and password
        $sql = mysqli_query($conn, "SELECT * FROM users WHERE email = '{$email}' AND password = '{$password}'");
        if (mysqli_num_rows($sql)>0) {
            //  if users credentials matched
            $row = mysqli_fetch_assoc($sql);
            $status ="Active now";
            // updating user status to active now if user login successfully
            $sql2 = mysqli_query($conn, "UPDATE users SET status = '{$status}' WHERE unique_id = {$row['unique_id']}");
            if ($sql2) {
                $_SESSION['unique_id'] = $row['unique_id']; // using this session we user unique_id in other php file
                echo "success";
            }
        } else {
            echo "Email or Password is incorrect!";
        }
    } else {
        echo "All input fields are required";
    }

?>



now next create new file as ("logout.php") in htdocs/chatapp/
like as /htdocs/chatapp/php/logout.php
write source code as :




<?php



session_start();

if(isset($_SESSION['unique_id'])){
    include_once "config.php";

    $outgoing_id = mysqli_real_escape_string($conn, $_POST['outgoing_id']);
    $incoming_id = mysqli_real_escape_string($conn, $_POST['incoming_id']); 
    $output = "";
    $sql = "SELECT * FROM messages
    LEFT JOIN users ON users.unique_id = messages.outgoing_msg_id
     WHERE (outgoing_msg_id = {$outgoing_id} AND incoming_msg_id = {$incoming_id}) 
    OR  (outgoing_msg_id = {$incoming_id} AND incoming_msg_id = {$outgoing_id}) ORDER BY msg_id ASC";
    $query = mysqli_query($conn, $sql);
    if(mysqli_num_rows($query)> 0 ) {
        while($row = mysqli_fetch_assoc($query)){
            if($row['outgoing_msg_id'] === $outgoing_id) {
               // if this is equal to then he is a msg sender
            $output .= '<div class="chat outgoing">
                         
                        <div class="details">
                        <p>'. $row['msg'] .'</p>      
                        </div>
                        <img src="php/images/'.$row['img'].'" alt="">
                        </div>';
            }else {
                // he is a reciever
            $output .= '<div class="chat incoming">
                        <img src="php/images/'.$row['img'].'" alt="">
                        <div class="details">  
                        <p>'. $row['msg'] .'</p>                       
                        </div>
                        </div>';
            }
        }
        echo $output;
    }
  
}else {
    header("login.php");   
}

?>






now next create new file as ("search.php") in htdocs/chatapp/
like as /htdocs/chatapp/php/search.php
write source code as :



<?php
session_start();

include_once "config.php";
$outgoing_id  = $_SESSION['unique_id'];
$searchTerm = mysqli_real_escape_string($conn, $_POST['searchTerm']);

$output = "";
$sql = mysqli_query($conn, "SELECT * FROM users WHERE NOT unique_id ={$outgoing_id} AND (fname LIKE '%{$searchTerm}%' OR lname LIKE '%{$searchTerm}%')");

if(mysqli_num_rows($sql)> 0) {
   
    include_once "data.php";
} else {
        $output .= "No user found related to your search";
}
echo $output;

?>








now next create new file as ("signup.php") in htdocs/chatapp/
like as /htdocs/chatapp/php/signup.php
write source code as :




















<?php 

session_start();
include_once "config.php";
$fname = mysqli_real_escape_string($conn, $_POST['fname']);

$lname = mysqli_real_escape_string($conn, $_POST['lname']);

$email = mysqli_real_escape_string($conn, $_POST['email']);

$password = mysqli_real_escape_string($conn, $_POST['password']);


if(!empty($fname) && !empty($lname) && !empty($email) && !empty($password)){

// let's check user email is valid or not
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {//if email is valid

    // let's check that email is already exists in database or not

    $sql = mysqli_query($conn, "SELECT email FROM users WHERE email = '{$email}'");

    if(mysqli_num_rows($sql) > 0) {
        // if email already exist
        echo "$email - This email already exist!";
    } else{
        // let's check user upload file or not

        if(isset($_FILES['image'])) {
            // if file is uploaded
            $img_name = $_FILES['image']['name']; // getting user uploaded img name
          
            $tmp_name = $_FILES['image']['tmp_name']; // this temporary name is used to save/move file in folder


            // let's explode image and get the last extention like jpg png
            $img_explode = explode('.', $img_name);
            $img_ext = end($img_explode); // here we get the extension of an user uploaded img file


            $extensions = ['jpg', 'jpeg','png']; // these are some valid image ext and we have store then in array
            if(in_array($img_ext , $extensions) === true){
                // if user uploaded img ext is matched with any array extension

                $time = time(); // this will return us current ...
                    // we need this time because when you uploading user img to in our folder we rename user file with current time
                    //so all the img file will have a unique name
                    
                    // let's move the user uploaded img to our particular folder
                    $new_img_name = $time.$img_name;

                    if(move_uploaded_file($tmp_name, "images/".$new_img_name)){

                        $status = "Active now";  // once user signed up then his status will be active now
                        $random_id = rand(time(), 10000000); // creating random id for user

                        // let's insert all user data inside table

                        $sql2 = mysqli_query($conn, "INSERT INTO users (unique_id, fname, lname, email, password, img, status)
                         VALUES('{$random_id}', '{$fname}','{$lname}','{$email}','{$password}', '{$new_img_name}', '{$status}')");

                         if($sql2) {
                                // if these data inserted
                                $sql3 = mysqli_query($conn, "SELECT * FROM users WHERE email = '{$email}'");
                                if(mysqli_num_rows($sql3)> 0  ){
                                    $row = mysqli_fetch_assoc($sql3);

                                    $_SESSION['unique_id'] = $row['unique_id']; // using this session we used user unique_id in other php file

                                    echo "success";
                                }
                         }else {
                             echo "Something went wrong!";
                         }
                    
                    }
                    
                


            }else {
                echo "Please select an Image file - jpeg, jpg, png!";
            }



        }else {
            echo "Please select an Image file";
        }
    }
     

}else {
    echo "$email - This is not a valid email!";
}



}else{
    echo "All input are required";
}







?>





now next create new file as ("users.php") in htdocs/chatapp/
like as /htdocs/chatapp/php/users.php
write source code as :





<?php


session_start();

include_once "config.php";
$outgoing_id  = $_SESSION['unique_id'];

$sql = mysqli_query($conn, "SELECT * FROM users WHERE NOT unique_id ={$outgoing_id}");
$output = "";
/*if(mysqli_num_rows($sql) == 1){
    $output .= "No user are available to chat";

} else
*/if(mysqli_num_rows($sql) > 0) {
    include_once "data.php";
  
}
echo $output;

?>





now next create new Folder as ("images") in htdocs/chatapp/
like as /htdocs/chatapp/php/images
// for save users images



//For create javascript folder 
now  create new Folder as ("javascript") in htdocs/chatapp/
like as /htdocs/chatapp/php/javascript/





now next create new file as ("chat.js") in htdocs/chatapp/javascript

like as   /htdocs/chatapp/javascript/chat.js
write source code as :










const form = document.querySelector(".typing-area"),
inputField = form.querySelector(".input-field"),
sendBtn = form.querySelector("button"),
chatBox = document.querySelector(".chat-box");

/*

form.onsubmit = (e)=>{
    e.preventDefault(); // preventing form from submiting
}

*/
/*
sendBtn.onclick = ()=> {
    // let's Start Ajax

    let xhr = new XMLHttpRequest(); // creating XML object
   
    xhr.onload = ()=>{
        if(xhr.readyState === XMLHttpRequest.DONE){
            if(xhr.status === 200){
                inputField.value = ""; //once message inserted into database then leave blank the input field
                scrollToBottom();
             
                
            }
        }

    }

    // we have to send the  form data through ajax to php
    
    let formData = new FormData(form); // creating new formData object
    
    xhr.send(formData); // sending  the form data to php
    
} */



 
setInterval(()=> {
    // let's Start Ajax

     let xhr = new XMLHttpRequest(); // creating XML object
     xhr.open("POST", "php/get-chat.php", true);
     xhr.onload = ()=>{
         if(xhr.readyState === XMLHttpRequest.DONE){
             if(xhr.status === 200){
                 let data = xhr.response;
                     chatBox.innerHTML = data; 
                     if(!chatBox.classList.contains("active")){
                        // if active class not contains in chatbox then scroll to buttom 
                      

                     }
                 }
                 
             }
         } 

          // we have to send the  form data through ajax to php
    
    let formData = new FormData(form); // creating new formData object

    xhr.send(formData); // sending  the form data to php
       
   }, 500); // this function will run frequently after 500ms


   function scrollToBottom(){
       chatBox.scrollTop = chatBox.scrollHeight; 
   }












now next create new file as ("login.js") in htdocs/chatapp/javascript

like as   /htdocs/chatapp/javascript/login.js
write source code as :




const form =  document.querySelector(".login form"),
continueBtn = form.querySelector(".button input"),
errorText = form.querySelector(".error-txt");

form.onsubmit = (e)=>{
    e.preventDefault(); // preventing form from submiting
}

continueBtn.onclick = ()=>{
    // let's Start Ajax

    let xhr = new XMLHttpRequest(); // creating XML object
    xhr.open("POST", "php/login.php", true);
    xhr.onload = ()=>{
        if(xhr.readyState === XMLHttpRequest.DONE){
            if(xhr.status === 200){
                let data = xhr.response;
                console.log(data);
                if(data == "success"){
                    location.href ="users.php";
            }else{
                errorText.textContent = data;

                errorText.style.display = "block";
                
            }       
        }
    }
}
   // we have to send the  form data through ajax to php
    
    let formData = new FormData(form); // creating new formData object

    xhr.send(formData); // sending  the form data to php
}








now next create new file as ("pass-show-hide.js") in htdocs/chatapp/javascript

like as   /htdocs/chatapp/javascript/pass-show-hide.js
write source code as :



const pswrdField = document.querySelector(".form input[type='password']"),
toggleBtn =document.querySelector(".form .field p");

toggleBtn.onclick = ()=>{
    if(pswrdField.type == "password"){
        pswrdField.type = "text";
     
        toggleBtn.textContent = "hide";
    } else {
        pswrdField.type = "password";
      
        toggleBtn.textContent = "show";
    }
}



now next create new file as ("signup.js") in htdocs/chatapp/javascript

like as   /htdocs/chatapp/javascript/signup.js
write source code as :



const form =  document.querySelector(".signup form"),
continueBtn = form.querySelector(".button input"),
errorText = form.querySelector(".error-txt");

form.onsubmit = (e)=>{
    e.preventDefault(); // preventing form from submiting
}

continueBtn.onclick = ()=>{
    // let's Start Ajax

    let xhr = new XMLHttpRequest(); // creating XML object
    xhr.open("POST", "php/signup.php", true);
    xhr.onload = ()=>{
        if(xhr.readyState === XMLHttpRequest.DONE){
            if(xhr.status === 200){
                let data = xhr.response;
                if(data == "success"){
                        location.href = "users.php";
                }else {
                    errorText.textContent = data;

                    errorText.style.display = "block";
                    
                }
                
            }
        }

    }

    // we have to send the  form data through ajax to php
    
    let formData = new FormData(form); // creating new formData object

    xhr.send(formData); // sending  the form data to php

}




now next create new file as ("users.js") in htdocs/chatapp/javascript

like as   /htdocs/chatapp/javascript/users.js
write source code as :

const searchBar = document.querySelector(".users .search input"),
searchBtn = document.querySelector(".users .search button"),
usersList = document.querySelector(".users .users-list"),
searchBtni = document.querySelector(".users .search button p");


searchBtni.onclick = ()=>{
    if(searchBtni.textContent == "Search!")
    {
        searchBtni.textContent= "Cancel!";

    }else{
        searchBtni.textContent = "Search!";
    }

}


searchBtn.onclick = ()=> {
    searchBar.classList.toggle("active");
    searchBar.focus();
    searchBtn.classList.toggle("active")
    searchBar.value = ""; 
   
    
    
}

searchBar.onkeyup = ()=>{
    let searchTerm = searchBar.value;
    if(searchBar != ""){
        searchBar.classList.add("active");
    }else{
        searchBar.classList.remove("active");
    }



    // let's Start Ajax

    let xhr = new XMLHttpRequest(); // creating XML object
    xhr.open("POST", "php/search.php", true);
    xhr.onload = ()=>{
        if(xhr.readyState === XMLHttpRequest.DONE){
            if(xhr.status === 200){
                let data = xhr.response;
                
                usersList.innerHTML = data;
                }
                
            }


        } 
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.send("searchTerm=" + searchTerm);  

}
    
setInterval(()=> {
     // let's Start Ajax

      let xhr = new XMLHttpRequest(); // creating XML object
      xhr.open("GET", "php/users.php", true);
      xhr.onload = ()=>{
          if(xhr.readyState === XMLHttpRequest.DONE){
              if(xhr.status === 200){
                  let data = xhr.response;
                  
                  if(!searchBar.classList.contains("active")){// if active not contains in search bar then add
                      usersList.innerHTML = data;
                  }
                  }
                  
              }
          } 
          xhr.send(); 
    }, 500); // this function will run frequently after 500ms






Finally get chat application to signup and login to chat each other

Post a Comment

3 Comments


  1. Warning
    : Undefined array key "user_id" in
    C:\xampp\htdocs\ChattingApp\chat.php
    on line
    14


    Fatal error
    : Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1 in C:\xampp\htdocs\ChattingApp\chat.php:15 Stack trace: #0 C:\xampp\htdocs\ChattingApp\chat.php(15): mysqli_query(Object(mysqli), 'SELECT * FROM u...') #1 {main} thrown in
    C:\xampp\htdocs\ChattingApp\chat.php
    on line
    1

    This is my error can you please respond me

    ReplyDelete
    Replies
    1. you should not copy paste the database mysql user table - sorce code.

      you may be create all table manually and impelement the code

      and check all case sensitive or spelling in the source code.

      here display syntax error : so solution is please check all spelling or case sensitive source code.

      thank you visiting our blog

      Delete

  2. Warning
    : Undefined array key "user_id" in
    C:\xampp\htdocs\ChattingApp\chat.php
    on line
    14


    Fatal error
    : Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1 in C:\xampp\htdocs\ChattingApp\chat.php:15 Stack trace: #0 C:\xampp\htdocs\ChattingApp\chat.php(15): mysqli_query(Object(mysqli), 'SELECT * FROM u...') #1 {main} thrown in
    C:\xampp\htdocs\ChattingApp\chat.php
    on line
    1

    This my error can you please respond me I dont what to do

    ReplyDelete

Close Menu