I'm trying to make a "sign in status" thing.
Here is a summary of what is happening.
User fills our field and jQuery request is sent.
Credentials are validated.
Screen displays a welcome message.
So I can get the welcome message sent back to me if the credentials are valid (or error if credentials are false), but here is where the issue resides...
I am having a really difficult time storing anything in PHP as a global variable using my only jQuery (no included file) approach... So my workaround was to take the passed message (Let's just say when credentials are valid, I pass back something like "X" or "1"), and then when the data comes back in the jQuery, I put an if statement in the callback, but it isn't working.
I know that the data being passed is matching what is being compared, and i've tested many different things to pass back, but the comparison is not being done.
Perhaps it isn't possible to do things like if statements in a jQuery callback, but also maybe I'm doing something wrong.
HTML:
<label>Sign In</label>
<br>
<label>Username</label>
<input type="text" id="name1">
<label>Password</label>
<input type="text" id="pass1">
<br>
<button type="submit" id="button2">Sign In</button>
<div id = "xx1">Status: Offline</div>
<div id = "xx2"></div>
jQuery:
$(document).ready(function(){
$("#button2").click(function(){
var name1=$("#name1").val();
var pass1=$("#pass1").val();
var key = "signIn";
$.ajax({
url:'rpc.php',
method:'POST',
data:{
name1:name1,
pass1:pass1,
key:key
},
success:function(data){
if(data === '1')
{
document.getElementById('xx1').innerHTML = "Status: Online";
}
document.getElementById('xx2').innerHTML = data;
//var p = data;
}
});
});
});
(xx2 is updating by the way)
Lastly, relevant bits of my rpc.php:
else if($_POST['key'] === "signIn")
{
$name1=$_POST['name1'];
$pass1 = $_POST['pass1'];
if($name1 !== "" && $pass1 !== "")
{
$sql = "SELECT * FROM whatever";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if($name1 === $row["username"])
{
$UNTrue = true;
if (password_verify($pass1, $row['password'])) {
$PassTrue = true;
}
}
}
} else {
//echo "0 results";
}
if($UNTrue === true && $PassTrue === true)
{
echo "1";
$conn->close();
}
else
{
echo "<p align=center style = 'color:#ba261b'>(Incorrect Username or Password) </p>";
$conn->close();
}
}
else
{
echo "<p align=center style = 'color:#ba261b'>(Please Fill Required Fields) </p>";
$conn->close();
}
}
So data is "1" in this scenario, as displayed to my via xx2, and xx1 remains as "Status: Offline".
I'm wondering if I have to store the data in a JavaScript variable first, and then later somehow referencing it again ASAP.
The other option would be to figure out how to use PHP global variables without file inclusion.
Is it possible even though you're echoing "1", it's getting interpreted as a number? Assuming the data response you get in the success callback is literally just what your PHP script echoes, that's the first thing that jumps out to me, since (1 === "1") is false.
Related
I need to get a value inside a div content. After a button click and doing stuff on the server side, my PHP function does:
echo "0";
or
echo "1";
depending on what my function does. So let's say if it's 0, the AJAX response will be $("div#divResult").html(data); where I put the 0 in the div divResult.
What I am trying to do now is I want to execute a js function to read whether it's 0 or 1 in divResult.
This is how I execute it:
<div id="divResult"><script>getDivResult();</script></div>
And my js function:
function getDivResult()
{
var result = $("div#divResult").text();
if(result === "0")
{
alert("Badge Number already exists, please check again.");
}
else if(result === "1")
{
alert("Your details have been entered!")
ADD_USER_POPUP.close;
}
}
Somehow the getDivResult function is not executing. The 0 and 1 does display on in the div though. Any help on this? I've tried .html too by the way.
EDIT:
Here's the AJAX that I use for the button click and return the response from PHP which is either 1 or 0:
$.post(page, {
name : name,
badge_number : badge_number,
category : category,
priviledge : priviledge,
action : "insert"
}, function(data) {
$("div#divResult").html(data);
});
2nd EDIT:
function insertRow($name, $badge_number, $priviledge, $category)
{
$table_info = "TBL_USER_LOGIN";
$query_string = "select badge_number from $table_info where badge_number = $badge_number";
$result = #mysql_query($query_string) or die (mysql_error());
$checkBadge = mysql_num_rows($result);
if($checkBadge>0)
{
//echo "Badge Number $badge_number already exists. Please check again.";
echo "0";
}
else
{
$query_string = "insert into $table_info(name, badge_number, priviledge, category) values('$name', '$badge_number', '$priviledge', '$category')";
$result = #mysql_query($query_string) or die (mysql_error());
//echo "Your details have been entered! Please click on 'View Users' to display all users.";
echo "1";
}
?>
<?php
$action = rtrim($_REQUEST['action']);
if($action=="delete")
{
$id = rtrim($_REQUEST['id']);
$order = $_REQUEST['order'];
echo deleteRow($id);
echo selectAll($order);
}
elseif($action=="insert")
{
$name = $_REQUEST['name'];
$badge_number = $_REQUEST['badge_number'];
$priviledge = $_REQUEST['priviledge'];
$category = $_REQUEST['category'];
echo insertRow($name, $badge_number, $priviledge, $category);
}
elseif($action=="update")
{
$order = $_REQUEST['order'];
echo selectAll($order);
}
?>
You shouldn't need to append the return data to the page at all. Why don't you run your function immediately after the AJAX request completes, like so:
$.ajax({
success: function(data) {
if(data === "0") {
alert("Badge Number already exists, please check again.");
}
else if(data === "1") {
alert("Your details have been entered!")
ADD_USER_POPUP.close();
}
}
});
place getDivResult() to onclick in which button you click like
< button onclick="getDivResult()">Click me< /button>"
i think it will be work with you.
enclose the echo with a div then trying getting the value by the id.
or
try echoing via json enconde
json_encode
then fetch the value by using AJAX
i think, this script <script>getDivResult();</script> was replaced the content of #divResult by ajax code $("div#divResult").html(data);. Instead of that, place the script inside head section rather than inside #divResult to execute that.
Where is your ajax? How do you do it?
It looks like you're using jQuery. Try reading the documentation
https://api.jquery.com/jquery.get/
You can try something like this:
$.get( "ajax/test.html", function( data ) {
if(data === "0")
{
alert("Badge Number already exists, please check again.");
}
else if(data === "1")
{
alert("Your details have been entered!")
ADD_USER_POPUP.close;
}
});
data should be your 0 or 1
When you do .html(data) all the existing elements wipedoff and replaced by new content:
$("div#divResult").html(data);
I guess you should do this:
$("div#divResult").html(data);
getDivResult(); // call after it. and put the function globally.
Run your function
getDivResult();
after
$("div#divResult").html(data);
in ajax
I have a simple JavaScript function that will not allow a form to be submitted if all the fields are not filled out. On top of that I would like PHP to write out an error message next to just the fields that are empty. The problem is the function activates upon the $_POST and yet my JavaScript function will not allow for $_POST to occur as long as one of the fields are empty.
If I keep the action outside of the $_POST condition then the page will load with the error message already showing. I am fairly new to PHP and JavaScript and would like any insight on perhaps another available condition that I could use to trigger my error messages to appear in my form. I am also open to any other suggestions for error handling. I do prefer to keep my JavaScript present due to it's ability to keep the form from being submitted if it is not properly filled. Unless there is another way to take that action then I have to keep the JavaScript.
PHP:
function cleanCrew ($id, $pswrd) {
$id = stripslashes($id);
$pswrd = stripslashes($pswrd);
$id = strip_tags($id);
$pswrd = strip_tags($pswrd);
return array($id, $pswrd);
}
require_once 'dbServ.php';
$db_server = mysqli_connect($db_host,$db_user,$db_pass,$db_base);
if ($db_server) {
$error_1 = "";
} else{
$error_1 = "connection to database unsuccessful";
}
$error_2 = "";
$error_3 = "";
if ($_POST) {
$user_id = mysqli_real_escape_string($db_server, $_POST['userId']);
$user_pass = mysqli_real_escape_string($db_server, $_POST['pass']);
$id_and_pass = cleanCrew($user_id, $user_pass);
if ($user_id == "" || $user_id == null) {
$error_2 = "please fill in proper User Id";
} else{
$error_2 = " ";
}
if($user_pass == "" || $user_pass == null){
$error_3 = "please fill out password";
} else{
$error_3 = " ";
}
echo $id_and_pass[0];
echo $id_and_pass[1];
}
HTML:
<div id="intro">
<h1 id="the_blog" align="center">The <span id="blog_animate" style="position:relative;">Blog</span></h1>
<div id="log-in"><p id="log">Log In</p><br> <?php echo $error_1; ?>
<form action="blog.php" method="post" onsubmit="return checkForm(this)" name="form1">
<p id="log">User ID :</p> <input type="text" placeholder="johnnyApple175" name="userId"></input><?php echo $error_2 ?><br>
<p id="log">Password:</p> <input type="password" name="pass"></input><?php echo $error_3; ?><br>
<input type="submit" value="submit" class="button" ></input>
</form>
First:
It's always a very good idea to validate the data server side, like you're doing.
Reason is simple: Javascript is client-side and can easily be modified to e.g. bypass those checks. Also, good that you escaped the sent data prior using it in the Database query.
Your problem is, that you're checking for $_POST to exist - it always exists, it's a super global var. You actually want to check if it's empty:
if (!empty($_POST))...
You might want to think over it, if you really want to give detailed information what exactly was wrong. Giving more info is more user friendly, but it makes attacks easier, especially if you don't block the user after X retries.
it's my first time asking here,
I've been trying to look for something similar in other questions asked, and couldn't find it.
I have a form with Zip code line(textbox) and State line(textbox),
now, the stateboxes are auto-filled by a javascript by entering a valid US zip code.
the form itself is a bit longer.
I only show the relevant code that has been edited by me,
It was a select menu before (and everything worked just fine - data was entered into databse), and I changed it, so no select will be needed.
There is also css file, but it's irrelevant (designing isn't the issue)
So, here is my html code :
<html>
<head>some content here</head>
<body>
<form method="post" action="process.php">
<div class="title"><h2>my form title</h2></div><br>
<div align="center" class="element-name">
</span>
<span align="center" id="zipbox" class="nameFirst">
<input type="text" class="medium" pattern="[0-9]*" name="col2" id="col2" maxlength="5" placeholder="Type your ZIP code" onkeypress='validate(event)'required/>
</span>
<span align="center" id="zipbox2" class="nameLast">
<input type="text" class="medium" pattern="[0-9]*" name="col4" id="col4" maxlength="5" placeholder="Type your ZIP code" onkeypress='validate(event)'required/>
</span></div>
<div align="center" class="element-name">
<span class="required"></span>
<span align="center" id="statebox" class="nameFirst">
<input type="text" class="medium" name="col1" id="col1" placeholder="" required />
<label class="subtitle">From</label>
</span>
<span align="center" id="statebox2" class="nameLast">
<input type="text" class="medium" name="col3" id="col3" placeholder="" required />
<label class="subtitle">To</label>
</span></div>
<p align="center"><input type="reset" value="Clear"></p>
</body>
</html>
some javescript !
<script src="//code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(document).ready(function() {
$("#col2").keyup(function() {
var el = $(this);
if (el.val().length === 5) {
$.ajax({
url: "http://zip.elevenbasetwo.com",
cache: false,
dataType: "json",
type: "GET",
data: "zip=" + el.val(),
success: function(result, success) {
$("#city").val(result.city);
$("#col1").val(result.state);
}
});
}
});
});
</script>
<script>
$(document).ready(function() {
$("#col4").keyup(function() {
var el = $(this);
if (el.val().length === 5) {
$.ajax({
url: "http://zip.elevenbasetwo.com",
cache: false,
dataType: "json",
type: "GET",
data: "zip=" + el.val(),
success: function(result, success) {
$("#city2").val(result.city);
$("#col3").val(result.state);
}
});
}
});
});
</script>
and php code to process the form :
- it's 13 columns, but i know for sure that the other values are correct.
- col0 represent the date.
<?php
require_once('recaptchalib.php');
$privatekey = "mycaptchakey";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
$process = FALSE;
} else {
// Your code here to handle a successful verification // Your code here to handle a successful verification
}
define('CONST_SERVER_TIMEZONE', 'EDT');
define('CONST_SERVER_DATEFORMAT', 'YmdHis');
$current_date = date("Y-m-d H:i:s");
$col0 = $_POST['col0'];
$col1 = strtoupper($_POST['col1']);
$col2 = strtoupper($_POST['col2']);
$col3 = strtoupper($_POST['col3']);
$col4 = strtoupper($_POST['col4']);
if ( isset($col1) && isset($col2) isset($col3) && isset($col4) && $error == FALSE ) {
$process = TRUE;
} else {
$process = FALSE;
}
$mode = "mysql";{
define ('DB_USER', 'uname');
define ('DB_PASSWORD', 'pass');
define ('DB_HOST', 'host');
define ('DB_NAME', 'dbname');
$dbc = #mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) or die('Failure: ' . mysql_error() );
mysql_select_db(DB_NAME) or die ('Could not select database: ' . mysql_error() );
$query = "INSERT INTO mytable VALUES ('$current_date','$col1','$col2','$col3','$col4')";
$q = mysql_query($query);
if (!$q) {
exit("<p>MySQL Insertion failure.</p>");
} else {
mysql_close();
//for testing only
//echo "<p>MySQL Insertion Successful</p>";
}}
header( 'Location: http://mywebsite.com/index.php' );
?>
i'm not sure if i'm doing it right but here is my
mytable structure :
1 - sid - int(11) AUTO_INCREMENT
2 - col0 - date
3 - col1 - text utf8_unicode_ci
4 - col2 - text utf8_unicode_ci
5 - col3 - text utf8_unicode_ci
6 - col4 - text utf8_unicode_ci
and so on up to 12 columons.
Help please ! what is going wrong here ?
EDIT :
Thank you very much r3wt for the usefull information,
there is a lot to fix especially when it comes to the php part of it :)
ok, so i was able to fix the insertion.
i missed a critical value -
$query = "INSERT INTO mytable VALUES ('$current_date','$col1','$col2','$col3','$col4')";
should have been:
$query = "INSERT INTO mytable VALUES ('','$current_date','$col1','$col2','$col3','$col4')";
that's is because all this form info is going into a phpGrid table
and i had a hidden column 'sid' which is automatically beeing filled.
I promise that in the next time I will be prepare with some more knowledge :)
thanks again.
This waits until a second has past after they have finished typing in the element, then submits the ajax request.
$(function(){
$("#col4").keyup(function() {
var col4val = $(this).val();
clearTimeout(timer);
timer = setTimeout(function(){fillLocation(col4val)}, 1000);
});
var timer = null;
function fillLocation(value){
$.get('http://zip.elevenbasetwo.com', {zip: value} , function(data){
var result = JSON.parse(data);
$("#city2").val(result.city);
$("#col3").val(result.state);
});
}
});
also, your php code is considered to be woefully insecure because you are using mysql.
also, i just noticed a glaring error, you are missing and and operator between $col2 isset and $col3, check your ajax i guarantee you it is returning 500 internal server error:
if ( isset($col1) && isset($col2) isset($col3) && isset($col4) && $error == FALSE ) {
$process = TRUE;
} else {
$process = FALSE;
}
also, your query is wrong. its obvious you are just copy and pasting things together here. go read the mysql manual on INSERT statements and go read up on the mysqli and pdo extensions for php.
A valid mysql statement looks like:
INSERT INTO mytable (column1,column2,column3) VALUES ('val1','val2','val3')
realizing this, you could construct the statement in php like so
$query = mysql_query("INSERT INTO mytable (column1,column2,column3) VALUES ('".$val1."','".$val2."','".$val3."')");
if you continue to use mysql you will get your site hacked, its just a matter of time, especially since you don't sanitize any of your data. please make the smart choice and use mysqli or pdo to interface with the database from php.
As per the request of Dikei, i'm going to introduce you briefly to prepared statements with mysqli so that you may learn to use safe methods for interacting with the database.
$mysqli = new mysqli('host','username','password','databasename');
$mysqli->set_charset("utf8");
$stmt = $mysqli->prepare("INSERT INTO mytable (column1,column2,column3) VALUES (?,?,?)");//bind your variables in the same order!
//s for a string, d for a double floating point integer, and i for unsigned int.
$stmt->bind_param('sss',$col1,$col2,$col3);
if($stmt->execute()) {
$row = $stmt->insert_id ?: null;
if(!empty($row))
{
//query success
}else{
//query failure
}
$stmt->close();
}
$mysqli->close();
if you need more info, i provided a broader example of working with mysqli using the Object Oriented approach here(its in part two of the answer): login session destroyed after refresh
So on this website I'm making (who knows if i'll actually finish it lol) when someone opens up the new user page, php echos into a javascript script all the usernames from the database to create an array.
<script type="text/javascript">
var allUsers = ['!' <?php
$result = mysql_query("SELECT username FROM users ") or die("error " .mysql_error());
$usersArray = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$usersArray[] = $row['username'] or die("error ". mysql_error());
}
foreach ($usersArray as $name) {
echo ',' . json_encode($name );
}
?> , ];
the point of this is to have a live checker so if you type in a username that already exists, red text shows up next to the username input. But let's say I get 1,000,000 users (completely theoretical). Fortunately, the array only gets created at the beginning of the web page load. But will the function that checks if the username already exists in the huge array and gets called everytime someone changes the text in the username input put too much stress on the script and crash the website? If so, is there a better way to do what I'm describing?
Here's the rest of the code
function contains(a, obj) {
var i = a.length;
while (i--) {
if (a[i] === obj) {
return true;
}
}
return false;
}
function onUserChange() { //gets called onkeypress, onpaste, and oninput
if(contains(allUsers, str)) {
div.innerHTML = "Username already exists";
div.style.color = "red";
userValid = false;
}
}
</script>
Something along these lines. ( with jQuery and PDO ) - note - code is not tested.
var keyTimer, request;
$('namefield').blur(function(){
onUserChange();
});
$('namefield').keyup(function(){
onUserChange();
});
function onUserChange() { //gets called onkeypress, onblur
keyTimer = setTimeout(function(){
if(request && request.readystate != 4){
//cancel a previous request if a new request is made.
request.abort();
}
request = $.post(
'http://yoursite.com/location/of/username/script.php', //post data to server
{username : $('namefield').val()},
function(data){
if(data == 0 ) { //might be a string here
alert( 'the name is ok to use.' );
}else{
alert( 'someone has this name already.' );
}
}
);
}, 500); //overwrite previous timeout if user hits key within 500 milliseconds
}
Then in the backend
$sql = 'SELECT id FROM users WHERE username = :username';
//insert from post username but we are good programers and are using PDO to prevent sql injection.
//search for the username in the db, count the number of users or rows should be 1 someone has it 0 no one has it assuming its unique.
$stmt = $Pdo->prepare($sql);
$stmt->execute(array(':username', $_POST['username']));
echo $stmt->rowCount();
exit();
etc.....
Do not do it. My counsel is to use ajax to load the php file that will make a query asking only for the user that was typed in the input and retunr only a boolean value(exists=true / notexists=false)
Code example:
HTML(yourFile.html):
<script>
jQuery(document).ready(function(){
//When the value inside the input changes fire this ajax querying the php file:
jQuery("#inputUser").change(function(){
var input = jQuery(this);
jQuery.ajax({
type:"post",
url:"path/to/file.php",
data:input.val(),
success: function(data){
//if php returns true, adds a red error message
if(data == "1"){
input.after('<small style="color:#ff0000;">This username already exists</small>');
//if php returns false, adds a green success message
} else if(data == "0"){
input.after('<small style="color:#00ff00;">You can use this username</small>');
}
}
});
});
});
</script>
<input id="inputUser" type="text" name="username" value="">
PHP(path/to/file.php):
<?php
$username = $_REQUEST['username']; // The value from the input
$res = mysqli_query("SELECT id FROM users WHERE username='".$username."'"); // asking only for the username inserted
$resArr = mysqli_fetch_array($res);
//verify if the result array from mysql query is empty.(if yes, returns false, else, returns true)
if(empty($resArr)){
echo false;
} else{
echo true;
}
?>
As I can see you need to load the PHP code when your website is loading.
First, I recommend you to separate the code. The fact that you can mix Javascript with PHP doesn't mean it is the best practice.
Second, yes, it's not efficient your code since you make Javascript load the result so you can search into it next. What I suggest you is making the search in the server side, not in client side, because as you say, if you have 100 elements maybe the best is to load all the content and execute the function, but if you have 1,000,000 elements maybe the best is to leave the server to compute so it can make the query with SQL.
Third, you can do all this using Ajax, using Javascript or using a framework like jQuery so you don't have to worry about the implementation of Ajax, but you only worry about your main tasks.
I can't seem to work this one out. Been a few days and still no progress after re-writing it more times than I can count on my hands.
Here is the Javascript (On same page as html)
Summary: User types text into the input box. That gets sent off to be processed, which then gets sent back and displayed on the screen in the box ID'd as DisplayText on the html page.
<script type="text/javascript">
function SendText() {
if (document.getElementById("Text").innerHTML == "") {
return;
} else
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("DisplayText").innerHTML = xmlhttp.responseText;
}
}
Text = document.getElementById("Text").value;
xmlhttp.open("GET", "php/Test.php?Chat=" + Text, true);
xmlhttp.send();
}
}
</script>
Here is the HTML (Same page as the script)
<div>
<p>
<span id="DisplayText">
TEXT GOES HERE
</span>
</p>
</div>
<form action="" onsubmit="SendText();">
<input type="" name="" id="Text" />
<input type="submit" value="Send" name="Send" />
</form>
The PHP code is here
<?php
session_start();
include ("Connect.php");
$Connection = mysqli_connect("localhost", "root", "", "chatsystem");
$Create = "CREATE TABLE " . $_SESSION["Username"] . "Chat(Username VARCHAR(255), Chat VARCHAR(255))";
////////////////////////////////////////////////////////////////////////////////
$DatabaseExist = $Connection->query("SELECT 1 FROM " . $_SESSION["Username"] . "Chat");
if ($DatabaseExist !== false) {
echo "Database exists";
doSomething();
} else {
echo "Database does not exist";
mysqli_query($Connection, $Create);
doSomething();
}
////////////////////////////////////////////////////////////////////////////////
function doSomething() {
// Get the sent chat
$Input = $_REQUEST["Chat"];
// Insert into the database the new chat sent
mysqli_query($Connection, "INSERT INTO " . $_SESSION["Username"] . "chat (`Username`, `Chat`) VALUES ('$_SESSION[Username], '$Input')");
// Select everything from the database
$Result = $Connection->query("SELECT * FROM " . $_SESSION["Username"] . "Chat");
// Display everything from the database in an orderly fashion
// --
// For the length of the database
// Append to a variable the next table row
// --
while ($Row = $Result->fetch_array()) {
// Make Variable accessable
global $Input;
// Append username to the return value
$Input = $Input . $Row["Username"] . " : ";
// Append chat to the return value
$Input = $Input . $Row["Chat"] . "<br />";
}
}
// Will return the value
echo $Input;
?>
My connection to the Database is fine. I'm using it on other pages that work.
So lets assume that's not the problem. :P
Any help or insight from anyone who knows or can think of something that is wrong, I would be very grateful for.
I'm new to AJAX.
You do a wrong test with
if (document.getElementById("Text").innerHTML == "")
It should be the same way you use to get the text for sending in the AJAX
if (document.getElementById("Text").value == "")
So check its value property and not its innerHTML as input elements do not have html content..
Be careful though because your code is wide-open to SQL injection attacks.
1st : use input's value property instead innerHTML
eg. use
if (document.getElementById("Text").value == "")
instead of
if (document.getElementById("Text").innerHTML == "")
2nd : use return false; at the form's onsubmit event; to prevent current page to be refreshed as you are using ajax. Otherwise the page will get refreshed and it wont display the php page's output,
eg. use
onsubmit="SendText(); return false;"
instead of just
onsubmit="SendText();"
Try AJAX Long Polling technique for chat application. Here is example
http://portal.bluejack.binus.ac.id/tutorials/webchatapplicationusinglong-pollingtechnologywithphpandajax