Am using following code to create chat system and store data to txt file. it does what i need but there is a small error while submitting data, when i type text and hit enter AJAX loads data from file chatdata.txt for a second,
Index.html
<?php
session_start();
//Create a session of username and logging in the user to the chat room
if (filter_input(INPUT_POST, 'username')) {
$_SESSION['username'] = filter_input(INPUT_POST, 'username');
}
//Unset session and logging out user from the chat room
if (isset($_GET['logout'])) {
unset($_SESSION['username']);
header('Location:index.php');
}
?>
<html>
<head>
<title>Simple Chat Room</title>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,400,300' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/style.css" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</head>
<body>
<div class='header'>
<h1>
SIMPLE CHAT ROOM
<?php // Adding the logout link only for logged in users ?>
<?php if (isset($_SESSION['username'])) { ?>
<a class='logout' href="?logout">Logout</a>
<?php } ?>
</h1>
</div>
<div class='main'>
<?php //Check if the user is logged in or not ?>
<?php if (isset($_SESSION['username'])) { ?>
<div id='result'></div>
<div class='chatcontrols'>
<form method="post" onsubmit="return submitchat();">
<input type='text' name='chat' id='chatbox' autocomplete="off" placeholder="ENTER CHAT HERE" />
<input type='submit' name='send' id='send' class='btn btn-send' value='Send' />
<input type='button' name='clear' class='btn btn-clear' id='clear' value='X' title="Clear Chat" />
</form>
<script>
// Javascript function to submit new chat entered by user
function submitchat() {
if ($('#chat').val() == '' || $('#chatbox').val() == ' ')
return false;
$.ajax({
url: 'chat.php',
data: {chat: $('#chatbox').val(), ajaxsend: true},
method: 'post',
success: function (data) {
$('#result').html(data); // Get the chat records and add it to result div
$('#chatbox').val(''); //Clear chat box after successful submition
document.getElementById('result').scrollTop = document.getElementById('result').scrollHeight; // Bring the scrollbar to bottom of the chat resultbox in case of long chatbox
}
})
return false;
};
// Function to continously check the some has submitted any new chat
setInterval(function () {
$.ajax({
url: 'chat.php',
data: {ajaxget: true},
method: 'post',
success: function (data) {
$('#result').html(data);
}
})
}, 1000);
// Function to chat history
$(document).ready(function () {
$('#clear').click(function () {
if (!confirm('Are you sure you want to clear chat?'))
return false;
$.ajax({
url: 'chat.php',
data: {username: "<?php echo $_SESSION['username'] ?>", ajaxclear: true},
method: 'post',
success: function (data) {
$('#result').html(data);
}
})
})
})
</script>
<?php } else { ?>
<div class='userscreen'>
<form method="post">
<input type='text' class='input-user' placeholder="ENTER YOUR NAME HERE" name='username' />
<input type='submit' class='btn btn-user' value='START CHAT' />
</form>
</div>
<?php } ?>
</div>
</div>
</body>
</html>
Chat.php
<?php
session_start();
$filename=$_SESSION['username'];
$nametxt= "$filename.txt";
$message='created successfully';
if (file_exists($nametxt)) {
$fh = fopen($nametxt, 'a');
} else {
$fh = fopen($nametxt, 'w');
fwrite($fh, $message."\n");
}
fclose($fh);
if(filter_input(INPUT_POST, 'ajaxsend') && filter_input(INPUT_POST, 'ajaxsend')==true){
// Code to save and send chat
$chat = fopen($nametxt, "a");
$data="<b>".$_SESSION['username'].':</b> '.filter_input(INPUT_POST, 'chat')."<br>";
fwrite($chat,$data);
fclose($chat);
$chat = fopen("chatdata.txt", "r");
echo fread($chat,filesize("$nametxt"));
fclose($chat);
} else if(filter_input(INPUT_POST, 'ajaxget') && filter_input(INPUT_POST, 'ajaxget')==true){
// Code to send chat history to the user
$chat = fopen($nametxt, "r");
echo fread($chat,filesize("$nametxt"));
fclose($chat);
} else if(filter_input(INPUT_POST, 'ajaxclear') && filter_input(INPUT_POST, 'ajaxclear')==true){
// Code to clear chat history
$chat = fopen($nametxt, "w");
$data="<b>".$_SESSION['username'].'</b> cleared chat<br>';
fwrite($chat,$data);
fclose($chat);
}
can someone help me sort error, why AJAX loads data from chatdata.txt while submitting data.
If you used index.html instead of index.php, this will not work!
Then after, You might have forgotten to change the "chatdata.txt" on line 22 to $nametxt.
I tried the change and it worked!!
Related
I am wanting to submit a form using ajax to go to my page 'do_signup_check.php'.
There it will check the email address the user entered against the database to see if there is a match.
If there is a match I want my ajax form to redirect the user to the login.php page.
If there isn't a match I want it to load my page 'do_signup.php'
for some reason the code seems to be doing nothing. Please can someone show me where I am going wrong?
My Ajax form:
<html lang="en">
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
<?php include 'assets/config.php'; ?>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('login.php',function(){}).hide().fadeIn(500);
}
});
});
});
</script>
</head>
<body>
<div class="sign_up_contain">
<div class="container">
<div class="signup_side">
<h3>Get Onboard.</h3>
<h6>Join the directory.</h6>
<form id="signup" action="" method="POST" autocomplete="off" autocomplete="false">
<div class="signup_row action">
<input type="text" placeholder="What's your Name?" name="name" id="name" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<input type="text" placeholder="Got an Email?" name="email" id="email" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<div class="g-recaptcha" style="margin-top:30px;" data-sitekey="6LeCkZkUAAAAAOeokX86JWQxuS6E7jWHEC61tS9T"></div>
<input type="submit" class="signup_bt" name="submit" id="submt" value="Create My Account">
</div>
</form>
</div>
</div>
</div>
</body>
</html>
My Do_Signup_Check.php page:
<?php
session_start();
require 'assets/connect.php';
$myName = $_POST["name"];
$myEmail = $_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn));
}
if (mysqli_num_rows($check) > 0) {
echo '1';
} else {
echo '0';
}
?>
Try to use input id 'submt' to trigger the form as such :
$("#submt").click(function(){
e.preventDefault();
//your logic
You have not included the jquery in your page, the function is also missing the closing parentheses.
Include the jquery at the top
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Replace your function with the following code:-
<script>
$(function () {
$('form').on('submit', function (e) {alert(123);
e.preventDefault();
$.ajax({
type: 'post',
url: 'receive-callback.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('login.php',function(){}).hide().fadeIn(500);
});
}
}
});
});
});
</script>
After receiving success in Ajax and doing all necessary logic (fadeOut etc) just relocate user to login.php:
window.location.href = 'path/to/login.php';
Otherwise, in error function (it is goes just after success function) do the next:
window.location.href = 'path/to/do_signup.php';
Upd:
In case you want to have some piece of code from another file, you can use jQuery method load.
$('#some-selector').load('path/to/course/login.php');
It's a very basic example of using 'load', go google around it to explore more.
Please Try this code.
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function (result) {
if(result == 0){
window.location.href = 'do_signup.php';
}else{
window.location.href = 'login.php';
}
});
My Do_Signup_Check.php page:
<?php
session_start();
require 'assets/connect.php';
$myName=$_POST["name"];
$myEmail=$_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn));
}
if(mysqli_num_rows($check) > 0){
echo json_encode(array('result'=>'1'));
exit;
}else{
echo json_encode(array('result'=>'0'));
exit;
}
?>
I hope this will work for you.
I'm new in php and I want to submit the form to func_login.php by AJAX, instead of using action="func_login.php". So I can handle the error on the same page when user fail to login.
but the AJAX is not working, the form submission skip/ignore the AJAX and direct to func_login php page. I don't know how to check/debug the error in AJAX. What's wrong is my code?
header.php
<form method="post" id="sign-in-form" action="func_login.php" enctype="multipart/form-data">
<div class="form-group">
<label for="mailInput">Email address</label>
<input type="email" class="form-control" id="mailInput2" aria-describedby="emailHelp" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="passInput">Password</label>
<input type="password" class="form-control" id="passInput2" placeholder="Password" name="password">
</div>
<button type="submit" class="border-0 bg-yellow btn-normal col mt-3" name="submit_login">Login</button>
</form>
func_login.php
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
$myemail = mysqli_real_escape_string($connection, $_POST['email']);
$mypassword = mysqli_real_escape_string($connection, $_POST['password']);
$sql = "SELECT * FROM users WHERE email = '".$myemail."'";
$result = mysqli_query($connection, $sql);
$count = mysqli_num_rows($result);
if($count == 1) {
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$salt = $row["salt"];
$db_encrypted_password = $row["password"];
if(password_verify($mypassword.$salt,$db_encrypted_password)){
echo "valid";
}else{
echo "invalid";
}
}
}
?>
js.php
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script defer src="https://use.fontawesome.com/releases/v5.5.0/js/all.js" integrity="sha384-GqVMZRt5Gn7tB9D9q7ONtcp4gtHIUEW/yG7h98J7IpE3kpi+srfFyyB/04OV6pG0" crossorigin="anonymous"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.bootstrapvalidator/0.5.0/js/bootstrapValidator.min.js"></script>
<script>
//...Some BootstrapValidotor Code
$('#sign-in-form').on('submit',function(e){
e.preventDefault();
$.ajax({
url: '/func_login.php',
data: {
myemail=$("#mailInput2").val(),
mypassword=$("#passInput2").val();
},
dataType: 'json',
type: 'POST',
success: function(data) {
header("location: welcome.php");
alert("true");
},
error: function(data) {
alert("false");
//HANDLE ERROR HERE (POP OUT SOME ERROR DIALOG AND STAY ON SAME PAGE)
}
});
});
</script>
PHP Header won't work in jquery
try this
$('#sign-in-form').on('submit',function(e){
e.preventDefault();
var redireectUrl = 'welcome.php';
$.ajax({
url: 'func_login.php',
data: {
myemail=$("#mailInput2").val(),
mypassword=$("#passInput2").val();
},
dataType: 'json',
type: 'POST',
success: function(data) {
window.location.href = redireectUrl;
alert("true");
},
error: function(data) {
alert("false");
//HANDLE ERROR HERE (POP OUT SOME ERROR DIALOG AND STAY ON SAME PAGE)
}
});
});
I have been trying to create a chatting system using php+ ajax + mysql.
<?php
session_start();
?>
<html>
<head>
<title>Live Table Data Edit</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">You Are : <?php echo $_SESSION['name'];
?></h3><br />
<div id="live_data"></div>
</div>
<div id="messages"></div>
<div class="area" style="display:none">
<textarea id="text" name="text"></textarea>
<input type="submit" id="sub" name="sub" value="Send" />
</div>
</div>
</body>
</html>
<script>
$(document).ready(function() {
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '.first_name', function() {
var id = $(this).data("id1");
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: id
},
dataType: "text",
success: function(data) {
$('#messages').html(data);
$("div.area").show();
}
});
}
fetch_chat();
$("#sub").click(function() {
var text = $("#text").val();
$.post('insert_chat.php', {
id: id,
msg: text
}, function(data) {
$("#messages").append(data);
$("#text").val('');
});
alert(text);
});
});
});
but the trouble is that when I try to insert a new message in mysql the messages is send to all the users in which i have clicked.
the fetch_chat.php
<html>
<head>
</head>
<body>
<?php
session_start();
$con=mysqli_connect('localhost','root','','test');
$id= $_POST['id'];
$sql="select * from users where id='$id'";
$res=mysqli_query($con,$sql);
$row=mysqli_fetch_array($res);
$user_to= $row['name'];
$sql1="select * from chats where user_from='$_SESSION[name]' AND
user_to='$user_to' OR user_to='$_SESSION[name]' AND user_from='$user_to'
order by id";
$res1=mysqli_query($con,$sql1);
if(mysqli_num_rows($res1)>0){
while($row=mysqli_fetch_array($res1)){
?>
<b> <?php echo $row['user_from']; ?>:</b>
<?php echo $row['msg']; ?><br /><br />
<?php
}
}
else
echo "No msgs <br />";
?>
</body>
</html>
and insert_chat.php is:
<html>
<head>
</head>
<body>
<?php
session_start();
$con=mysqli_connect('localhost','root','','test');
$id= $_POST['id'];
$msg=$_POST['msg'];
$sql="select * from users where id='$id'";
$res=mysqli_query($con,$sql);
$row=mysqli_fetch_array($res);
$user_to= $row['name'];
$sql1="insert into chats(user_from,user_to,msg)
values('$_SESSION[name]','$user_to','$msg')";
$res1=mysqli_query($con,$sql1);
if($res1){
?>
<b> <?php echo $_SESSION['name']; ?>:</b>
<?php echo $msg; ?><br /><br />
<?php
}
?>
</body>
</html>
I don't know where I am going wrong. Please help me with this.
For example, the list of users is:
(1) user a
(2) user b
(3) user c
So at first I clicked a then I changed my mind to select b and send the text. But there arises the problem: the data gets inserted for both a and b like I am texting both of them at the same time.
You keep on adding more and more "click" event handlers to "sub", every time you click on "first_name". So then each time you click sub again, it runs all the previous event handlers again and again. So you get the current message, but sent to all users you previously clicked on since you loaded the page.
$("#sub").click(function() {
needs to be
$("#sub").off("click").on("click", function() {
so that it removes previous handlers before you define the new version with new data.
I'm trying to get a pop-up message saying if it was successfully submitted or not without having to go to a different page.
Now chrome gives me the pop-up message but it redirects me to a blank page after.
Here is my current code.
<?php
include "header.php";
include "conexao.php";
echo "<h1 align='center'>Pagina para alterar produtos</h1><div class='container'><hr>";
$referencia=$_GET['id'];
$sql = "SELECT * ";
$sql = $sql . " FROM tb_produto ";
$sql = $sql . " WHERE pr_codigo='".$referencia."'";
$produtos = $db->query($sql);
foreach ($produtos as $produto) {
$referencia = $produto["pr_codigo"];
$nome = $produto["pr_descricao"];
$preco = $produto["pr_preco"];
$disponivel = $produto["disponivel"];
}
echo "<h2>Referencia: ".$referencia."</h2>";
echo "<h2>Nome: ".$nome."</h2><hr>";
?>
<form action="confirmaAlterar.php">
<div class="form-group">
<label>Referencia</label>
<input class="form-control" type="text" name="referencia" value="<?php echo $referencia?>">
</div>
<div class="form-group">
<label>Nome</label>
<input class="form-control" type="text" name="nome" value="<?php echo $nome?>">
</div>
<div class="form-group">
<label>Preço</label>
<input class="form-control" type="text" name="preco" value="<?php echo $preco?>">
</div>
<button class="btn btn-primary">Alterar</button>
</form>
Here is where it submits the information of the form.
<?php
include "header.php";
include "conexao.php";
$nome=$_GET['nome'];
$referencia=$_GET['referencia'];
$preco=$_GET['preco'];
$sql="UPDATE tb_produto SET pr_descricao='".$nome;
$sql.="', pr_preco=".$preco;
$sql.= " WHERE pr_codigo='".$
try{
$comando=$db->prepare($sql);
$comando->execute();
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
header( "refresh2;Location:index.php" );
}
catch (PDOException $e){
echo "A";
}
To pass values using ajax. Form:
<form id="form">
<input type="text" value="test" name="akcija">
</form>
All inputs fields values in your form will be passed.
Ajax:
jQuery(function(){
$('#form').on('submit', function (e) { //on submit function
e.preventDefault();
$.ajax({
type: 'post', //method POST
url: 'yoururl.php', //URL of page where u place query and passing values
data: $('#form').serialize(), //seriallize is passing all inputs values of form
success: function(){ //on success function
$("#input").attr("disabled", true); //example
$("#input").removeClass('btn-primary').addClass('btn-success');//example
},
});
}
});
And on the ajax page you can get values by
$akcija = $_POST['akcija']
for this Problem you must use ajax method .
1- create html form and all input Required .
<form id="contactForm2" action="/your_url" method="post">
...
</form>
2- add jQuery library file in the head of html page .
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
...
3- add this method Under the jQuery library
<script type="text/javascript">
var frm = $('#contactForm2');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if(data == 'pass')
alert('ok');
else(data == 'fail')
alert('no');
}
});
ev.preventDefault();
});
</script>
4- in your_url .php file
<?php
$a = ok ;
if( $a == 'ok' ){
echo 'pass';
}else{
echo 'fail';
}
?>
this top answer is easy management form with jquery , but you need managment Complex form better use this library http://jquery.malsup.com/form/
This code works very well for chatting. I have added ajaxcall.php for real time notification. The problem is; instead of displaying a typing notification when other users are typing, it will be displaying myself whenever am typing.please how do i make it to show other users typing.
index.php
<?php
ob_start();
?>
<?php
session_start();
?>
<!doctype>
<html>
<head>
<title>Chat</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script type="text/javascript" src="jscolor.js"></script>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function() {
$.ajaxSetup(
{
cache: false,
beforeSend: function() {
$('#messages').hide();
$('#messages').show();
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
},
complete: function() {
$('#messages').hide();
$('#messages').show();
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
},
success: function() {
$('#messages').hide();
$('#messages').show();
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
}
});
var $container = $("#messages");
$container.load('ajaxload.php?id=<?php echo htmlentities( $_GET['id'], ENT_QUOTES, "UTF-8"); ?>');
var refreshId = setInterval(function()
{
$container.load('ajaxload.php?id=<?php echo htmlentities( $_GET['id'], ENT_QUOTES, "UTF-8"); ?>');
}, 3000);
$("#userArea").submit(function() {
$.post('ajaxPost.php', $('#userArea').serialize(), function(data) {
$("#messages").append(data);
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
document.getElementById("output").value = "";
});
return false;
});
});
</script>
<!--Ajax Server Call-->
<script>
function getAjaxFromServer(str){
if (str.length==0){
document.getElementById("ajaxResponse").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("ajaxResponse").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",'ajaxcall.php?id=<?php echo htmlentities( $_GET['id'], ENT_QUOTES, "UTF-8"); ?>',true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="chatwrapper">
<!--display-->
<!--http://www.youtube.com/watch?v=FyXeOX-uYMc-->
<div id="messages"></div>
<!--post-->
<form id="userArea">
<div id="usercolor">
<input name="reciever" type="hidden" value="<?php echo htmlentities($_GET['id'], ENT_QUOTES, "UTF-8");?>"><br>
<input name="text" class="color" id="text" maxlength="6" value="000000" />
</div>
<div id="messagesntry">
<textarea id="output" name="messages" placeholder="Message" onkeyup="getAjaxFromServer(this.value)"/></textarea>
</div>
<div id="messagesubmit">
<input type="submit" value="Post message" id="submitmessage" />
</div>
</form>
</div>
</body>
</html>
ajaxload.php
<?php
ob_start();
?>
<?php
session_start();
?>
<?php
include('connect.php');
$id=$_GET['id'];
$result = $db->prepare("SELECT * FROM messages ORDER BY id ASC");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
echo '<div style="color:'.$row['textcolor'].'">' .$row['user'] . ' : '. $row['message'] .'</div>';
}
?>
ajaxcall.php
<?php
ob_start();
?>
<?php
session_start();
?>
<?php
$txt=strip_tags($_GET['id']);
$txt1=strip_tags($_SESSION['SESS_MEMBER_ID']);
echo $txt;
echo " is typing ";
?>
The idea is to store a flag on a database and have an a .setTimeOut on your script on which will run whenever your field flag turns from 0 to 1
here is the code snippet to try
$('#txt_message').keyup(function(){
// Start a flag loop with an id of 'loop' and a counter.
var i = 1;
var dataString = 'flag='+ i ;
$.ajax({
type: "POST",
url: "notif.php",
data: dataString,
cache: false,
success: function(url){
}
});
this snippet will update your database whenever you type on your text field
var timer;
function AjaxRetrieve()
{
$.get("type_on.php?flag=0",function(data)
{
window.clearTimeout(timer);
$("#typing_on").html(data);
timer=window.setTimeout(function(){AjaxRetrieve()},3100);
});
}
timer=window.setTimeout(function(){AjaxRetrieve()},1300);
this snippet will be the one to update your flag after a few seconds