How to show typing message through Php using Ajax Mysql
Repository
What Will I Learn?
- You will learn how to get data from html element using jQuery selector
- You will learn how to send data using jquery ajax
- You will learn how to insert data to mysql
- You will learn how to show run time data to other person.
Requirements
- You know about basic HTML
- You know about basic PHP
- You know about basic MySQL
- You know about basic JavaScript
- You have to host the jQuery file
- To practice this tutorial you should have a webserver, text editor and a browser. In this tutorial I use XAMPP for webserver, Dreamweaver CS6 for text editor and Google Crome for browser.
Difficulty
- Intermediate
Tutorial Contents
First of all we discuss about Ajax. Ajax is used to perform actions on the application via the browser and forwarded to the webserver. Usually after clicking the submit button on the form will refresh the browser, AJAX can submit to the webserver without refresh the browser, even ajax can access the database in one event. For more detail, Let's pay attention steps bellow :
Now ReActive your webserver. create new folder in Xampp/htdocs/ if you use XAMPP.
Open your text editor software, Create new file and save as
index.php
in the previous folder that created by you.
Creating Form
- Create a simple form to insert data ,For Example I just create three textfield to insert name , email and submit button in the form action tag.
<form action="" method="post">
<input type="text" id="user_name" name="user_name" placeholder="User Name" />
<input type="password" id="password" name="password" placeholder="Password" />
<input type="submit" name="user" />
</form>
Code Explanation : we set these fields name for getting their data in php.
Now we create database
create table show_message.user (id int Not Null AUTO_INCREMENT , name varchar(50) Not Null , password varchar(50) Not Null , PRIMARY KEY(id));
create table show_message.typing_message (receiver_id int, sender_id int , typing_message varchar(255));
create table show_message.messages (message_id int NOT NULL AUTO_INCREMENT, message varchar(255) , receiver_id int , sender_id int , PRIMARY KEY(message_id) )
Code Explanation : we create 3 table in
'show_message'
database.'user'
table is creating to store'user name'
and'password'
data .'typing_message'
table is creating to store those message that is type before send.'messages'
table is creating to store'messages'
.
If you don't create it manually you can DOWNLOAD 'show_message.sql'
file here and import it into your sql
Addinh Php to Index.php
- Now write php script at the top of the
index.php
.
if(isset($_POST["user"]) && !empty($_POST["user_name"]) && !empty($_POST["password"])){
$con = mysqli_connect("localhost","root","","show_message");
$user_name = $_POST["user_name"];
$password = $_POST["password"];
$result = mysqli_query($con, "select * from user where name = '$user_name' and password='$password' ");
if(mysqli_num_rows($result) == 0){
mysqli_query($con,"insert into user(name,password) value('$user_name','$password')");
$result = mysqli_query($con, "select * from user where name = '$user_name' and password='$password' ");
$row = mysqli_fetch_assoc($result);
$id = $row["id"];
header('Location:message.php?id='.$id);
}
else{
$row = mysqli_fetch_assoc($result);
$id = $row["id"];
header('Location:message.php?id='.$id);
}
}
Code Explaination :In
if
condition we use'isset($_POST["user"])'
for check that , is that action againstuser
or not? Then we check that is all other fieldsempty
or not?'$con = mysqli_connect("localhost","root","","show_message");'
this script is a connection to the mysql. then we get these other fields data user_name and password. then we check it on the database table'user'
, is that user already exist or not? if'yes'
then it will login and go to next page'messsage.php'
and if'no'
then they insert their data to the database and then this user login and go to next page'message.php'
.
Create File
Create new file and save as
'message.php'
in the previous folder where'index.php'
file is saveCreate a simple form to insert message , show message and show typing message from other side, For Example I just create three fields to insert message , show message and show typing message in
'message.php'
And also create a'<Select>'
tag option where other users will show.
<div class="main">
<div id="show_message">
</div>
<div id="show_typing_message">
Typing...
</div>
<input type="text" id="insert_message" placeholder="Insert message" />
</div>
<select id="select_user">
<option></option>
</select>
Adding Php script
- As we know we get all users from database and add it on the
'<Select>'
tag.
<select id="select_user">
<?php
$con = mysqli_connect("localhost","root","","show_message");
$result = mysqli_query($con,"select * from user");
while($row=mysqli_fetch_assoc($result)){
$user_name = $row["name"];
$ids = $row["id"];
if($ids == $id){}
else{
?>
<option value="<?php echo $ids ?>"><?php echo $user_name ?></option>
<?php
}
}
?>
</select>
Code Explanation : here we create a connection to the database for getting all users. then we select all users from
'user'
table and fetch their'user_name'
and'user_id'
.
Adding jQuery AJAX
- As we know, to use jQuery we need to install or host it. Or we can also add jQuery CDN if we don't want to install or host it. we also have many choices CDN that we can use, either Google CDN or Microsoft CDN. For more Detail you can visit jquery official web . In this tutorial I use Google CDN. Add the CDN in
'<head>'
element.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
- To write the jQuery Script we should open
'<script>'
tag. You can put it in'<head>'
element or in` element.
Before add more event in jQuery. There is an event that we should add for the first. It is 'on input()'
event. this event get user name and typing message that you type in 'insert message'
. this event is call when you type a message . then it will load jQuery script. So, all jQuery Script must write in this function event.
$('#insert_message').on('input',function(){
var input = $("#insert_message").val();
var receiver_id = $("#select_user").val();
var sender_id = $("#id").html();
$.ajax({
url:'insert_typing.php',
method:'POST',
data:{
input:input,
sender_id:sender_id,
receiver_id:receiver_id
},
success:function(data){
}
});
});
Code Explanation : In this code we get user name from
'<Select>'
tag that is called'receiver_id'
and get typing message form'input'
and get user id that is called'sender_id'
, this is logged in user id. then send these values to the'insert_typing.php'
.
Create new file
- Create new file
'isnert_tying.php'
for getting values from'message.php'
. and write php script in'insert_typing.php'
if(isset($_POST["input"])){
$typing_message = $_POST["input"];
$receiver_id = $_POST["receiver_id"];
$sender_id = $_POST["sender_id"];
$con = mysqli_connect("localhost","root","","show_message");
$result = mysqli_query($con,"select * from typing_message where sender_id = '$sender_id' and receiver_id = '$receiver_id'");
$rows_count = mysqli_num_rows($result);
if($rows_count == 0){
mysqli_query($con,"insert into typing_message (sender_id, receiver_id, typing_message) value('$sender_id','$receiver_id','$typing_message')");
}
else{
mysqli_query($con,"update typing_message set typing_message = '$typing_message' where sender_id='$sender_id' AND receiver_id='$receiver_id' ");
}
}
Code Explanation : Here we check input value that is coming from
'message.php'
. then we get these values for example:'input'
as'typing_message'
,'receivere_id'
as'receiver_id'
and'sender_id'
as'sender_id'
. then we check these values form'typing_message'
table. if these values are not available in table then we insert these values to the'typing_message'
table. if these values are available in table then we update these values on the'typing_message'
table.
Adding jquery Ajax
- In jQuery there is an other event. It is ready() event. It will get data from database related to the
'user'
that is logged in. And it will get data after every 1 second.
$(document).ready(function(){
setInterval(function(){
var id = $("#id").html();
var send_id = $("#select_user").val();
$("#show_typing_message").load("get_typing_message.php?id="+id+'//'+send_id);
}, 1000);
});
Code Explanation : Here we get user id that is logged in and get value of the other user that is connected to us. And then send this values to the
'get_tying_message.php'
file. And this file return a result that is showing in'show_typing_message'
div.
Create new file
- Create new file called
'get_typing_message.php'
and write php script for getting typing_message that is write from other side
$id= $_GET["id"];
$split = explode("//",$id);
$receiver_id = $split[0];
$sender_id = $split[1];
$con = mysqli_connect("localhost","root","","show_message");
$result = mysqli_query($con,"select * from typing_message where sender_id = '$sender_id' AND receiver_id = '$receiver_id' ");
$row=mysqli_fetch_assoc($result);
$typing_message = $row["typing_message"];
echo $typing_message;
Code Explanation : Here we get typing message that is type from other user. And return this message.
Adding jquery Ajax
- In jQuery there is an other event. It is
'onkeyup()'
event. It will send data to the database. This event is call when you type a message.
$("#insert_message").on('keyup', function (e) {
if (e.keyCode == 13) {
var input = $("#insert_message").val();
var receiver_id = $("#select_user").val();
var sender_id = $("#id").html();
$.ajax({
url:'insert.php',
method:'POST',
data:{
input:input,
sender_id:sender_id,
receiver_id:receiver_id
},
success:function(data){
$("#insert_message").val(" ");
}
});
}
});
Code Explanation : Here we get
'insert_message'
,'id'
that is user logged in value and'receiver_d'
that is select from'<select>'
tag. then these values send to the'isnert.php'
for insert data to t he database.
Create new file
- Create new file
'insert.php'
and write php script for sending data to the database. this data is call message data.
if(isset($_POST["input"])){
$message = $_POST["input"];
$receiver_id = $_POST["receiver_id"];
$sender_id = $_POST["sender_id"];
$con = mysqli_connect("localhost","root","","show_message");
if($message != ''){
mysqli_query($con,"insert into messages(sender_id,receiver_id,message) value('$sender_id','$receiver_id','$message')");
}
}
Code Explanation : Here we get these values
'insert_message'
,'sender_id'
and'receiver_id'
. And then send these values to the'messages'
table.
Adding jquery Ajax
- In jQuery there is an other event. It is ready() event. It will get data from database related to the
'user'
that is logged in. And it will get data after every 1 second. These data are like message data.
$(document).ready(function(){
setInterval(function(){
var id = $("#id").html();
var sender_id = $("#select_user").val();
$("#show_message").load("get_message.php?id="+id+'//'+sender_id );
}, 1000);
});
Code Explanation : Here we get
'user id'
that is logged in and get value of the other user that is connected to us. And then send this values to the'get_message.php'
file. And this file return a result that is showing in'show_message'
div.
Create new file
- Create new file
'get_message.php'
and write php script for sending data to the database. this data is call message data.
$id= $_GET["id"];
$split = explode('//',$id);
$receiver_id = $split[0];
$sender_id = $split[1];
$con = mysqli_connect("localhost","root","","show_message");
$result = mysqli_query($con,"select * from messages where receiver_id='$id' and sender_id = '$sender_id' || receiver_id='$sender_id' and sender_id = '$id' order by message_id asc");
while($row=mysqli_fetch_assoc($result)){
$message = $row["message"];
$sender_id_1 = $row["sender_id"];
$receiver_id_1 = $row["receiver_id"];
if($sender_id_1 == $sender_id){
echo '<div style="text-align:left; width:100%; border-radius:5px; padding:5px; background:red; margin-top:5px;" >'.$message.'</div>';
}
else{
echo '<div style="text-align:right; width:100%; background:blue; padding:5px; margin-top:5px;" >'.$message.'</div>';
}
}
Code Explanation : Here we get
'sender_id'
and'receiver_id'
. And then get all message from'messages'
table related to that'receiver_id'
and'sender_id'
. Here we separate message in two div. one dive show those message that we send to the user and other div show those message that other user send.
Thank you for your contribution.
Your tutorial has some errors:
"For Example I just create three textfield to insert name , email and submit button in the form action tag."
You didn´t create 3 text fields, only 2. The third is a button.
"table is creating to store", he should say is "created", his English is confusing
You didn´t show the command to create the database "show_message"
....
Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]
sir i submit message through key 'Enter'. so that's why i didn't set submit button. And thank you so much for your response.