fetch data using ajax in php - php

I have two tables in my database first one id and the other one text.
I can fetch the data from db like this way
this is index.php file
<?php include "config.php"?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>
<ul>
<?php
$result = $db->query("select * from veri ORDER BY id DESC ");
while ($row = $result->fetch_object()) {
echo '<li id="'.$row->id.'">'.$row->text.'</li>';
}
?>
</ul>
</body>
</html>
I am required to check the database every five seconds if a new item inserted or not.
I am using this code below.But It doesnt work.I have no idea what is wrong ?can you please help and thank in advance
ajax.js file
$(function () {
$ajaxLoad = function () {
var lastid = $("ul li:first").attr("id");
$.ajax({
type: "post",
url: "ajax.php",
data: {"lastid": lastid},
dataType: "json",
success: function (result) {
if (result.error) {
$("#result").html(result);
}
else{
$("ul").prepend(result.data);
}
}
});
}
setInterval("ajaxLoad()",5000);
});
this ajax.php file
<?php
require "config.php";
if ($_POST) {
$lastid = $_POST["lastid"];
if (!$lastid) {
$array["error"] = "something is wrong";
} else {
$query = $db->query("select * from veri where id>$lastid ORDER by id DESC ");
if (mysqli_affected_rows()) {
while ($row = $query->fetch_object()) {
$array["data"]='<li id="'.$row->id.'">'.$row->text.'</li>';
}
} else {
$array["error"] = " there is no new record";
}
}
echo json_encode($array);
}
?>

Your setInverval() accepts a callback function as first parameter. You passed a string. It should be:
setInterval(ajaxLoad, 5000);
And also, remove the $ from the $ajaxLoad definition. It's JavaScript, not PHP. In case that you would want to prepend the $ to your variable, you must also use that variable along with the $ like so:
$variable = 5;
console.log($variable); // prints 5 to the console
However, it is absolutely bad practice since you will get confused as to whether you are using PHP or JS.
Here also you did a mistake. As per the current code you may get only last record inserted instead of all new inserted records because you are not concatenating the records. This is one way to solve it:
<?php
require "config.php";
if ($_POST)
{
$lastid = $_POST["lastid"];
if (!$lastid)
{
$array["error"] = "something is wrong";
}
else
{
$query = $db->query("select * from veri where id>$lastid ORDER by id DESC ");
if (mysqli_affected_rows())
{
$new_rows = "";
while ($row = $query->fetch_object())
{
$new_rows .= '<li id="'.$row->id.'">'.$row->text.'</li>';
}
$array["data"]=$new_rows;
}
else
{
$array["error"] = " there is no new record";
}
}
echo json_encode($array);
}
?>

Related

display data from database using ajax,mysql,php

Currently, I made script, which after onclick event,sending question to the database and showing data in console.log( from array ). This all works correctly, but.. I want to show data from array in the different position in my code. When I try to use DataType 'json' and then show some data, then it display in my console.log nothing. So, my question is: How to fix problem with displaying data? Is it a good idea as you see?
Below you see my current code:
$(document).ready(function(){
$(".profile").click(function(){
var id = $(this).data('id');
//console.log(id);
$.ajax({
method: "GET",
url: "../functions/getDataFromDB.php",
dataType: "text",
data: {id:id},
success: function(data){
console.log(data);
}
});
});
});
:
public function GetPlayer($id){
$id = $_GET['id'];
$query = "SELECT name,surname FROM zawodnik WHERE id='".$id."'";
$result = $this->db->query($query);
if ($result->num_rows>0) {
while($row = $result->fetch_assoc()){
$this->PlayerInfo[] = $row;
}
return $this->PlayerInfo;
}else {
return false;
}
}
:
$info = array();
$id = $_GET['id'];
$vv = new AddService();
foreach($vv->GetPlayer($id) as $data){
$info[0] = $data['name'];
$info[1] = $data['surname'];
}
echo json_encode($info);
I think it would be better to change the line fetch_all in mysqli to rm -rf. That information in the DB is all obsolete, or completely not true.
Try this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button class="profile" data-id="1">Click</button>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$(".profile").click(function(){
var id = $(this).data('id');
console.log(id);
$.ajax({
method: "GET",
url: "../functions/getDataFromDB.php",
dataType: "json",
data: {id:id},
success: function(data){
console.log(data);
$.each(data, function(idx, item) {
console.log(item.surname);
});
}
});
});
});
</script>
</body>
</html>
PHP side:
<?php
class AddService {
public function GetPlayer($id) {
if (filter_var($id, FILTER_VALIDATE_INT) === false) {
return false;
}
$query = "SELECT name, surname FROM zawodnik WHERE id={$id}";
$result = $this->db->query($query);
if ($result->num_rows <= 0) {
return false;
}
// assumming you are using mysqli
// return json_encode($result->fetch_all(MYSQLI_ASSOC));
// or
WHILE ($row = $result->fetch_assoc()) {
$data[] = $row;
}
return json_encode($data);
}
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$vv = new AddService();
// you don't need foreach loop to call the method
// otherwise, you are duplicating your results
echo $vv->GetPlayer($id);
}

How do we pass data in ajax? [duplicate]

This question already has answers here:
How can I get the data-id attribute?
(16 answers)
Closed 5 years ago.
I am new to Ajax and I am confused as to how we pass data in Ajax. I have an index.php file which displays some data, it has a link to delete the record, now the problem is, I am not able to figure out how to transfer the id value from index.php of the selected record to ajax file. Also, how should I go about once I have fetched the value in delete.php page where lies the code to delete records.
I have coded as below.
index.php
<div id="delMsg"></div>
<?php
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"select * from member");
$col=mysqli_num_fields($data);
echo "<table>";
while($row=mysqli_fetch_array($data))
{
echo "<tr>";
for($i=0;$i<$col;$i++)
{
echo "<td>".$row[$i]."</td>";
}
echo "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
echo"</tr>";
}
echo "</table>";
?>
ajax-file.js
$(document).ready(function(){
$(".del").click(function(event){
event.preventDefault();
$.ajax({
url:"delete.php",
method:"get",
data:{id:'ID'},
dataType:"html",
success:function(str){
$('#delMsg').html(str);
}
})
})
})
delete.php
<?php
$id=$_GET['id'];
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"delete from member where id='$id'");
if($data)
{
echo "success";
}
else
{
echo "error";
}
?>
Hopefully this conveys the idea of how an AJAX call works.
The first thing we want to do is setup our trigger, which in your case is a button with an onclick event.
<script
src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<!-- <button id="delete">Delete Something</button> -->
<button id="delete" onclick="onClickHandler(5)">Delete Something</button>
<p id="message">AJAX</p>
<script>
/* Notice I removed the document ready */
function onClickHandler(id)
{
event.preventDefault();
$.ajax(
{
url:"delete.php",
method:"POST", /* In the real world you want to use a delete here */
data: { /* plugin your data */
id: id,
name: "Bob",
age: 25
},
dataType:"html",
success: function(success) {
// Handle the success message here!
if (success) {
$('#message').text("Your message was received!");
}
},
error: function(error) {
// Handle your errors here
$('#message').text("Something went wrong!");
}
});
};
</script>
Notice how my data is prepared in the data object. I leave it up to you to figure out how to grab data and set it in the right field. You could: $('#someId').value(); or pass it through a function. If this is a source of confusion I can clarify.
data: { /* plugin your data */
id: 1,
name: "Bob",
age: 25
},
Next, we need to setup our script.
delete.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Obviously validate the data.
// But this is how you access it.
// $_POST is a global array, so you can access it like so:
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
// Do your server side stuff...
$sql = "DELETE FROM member
WHERE id = '{$id}' AND name = '{$name}' AND age = '{$age}'";
// Do your SQL (delete) here
// $con = mysqli_connect("localhost","root","","ajaxtest");
// Use prepared statements http://bobby-tables.com/php
// $data = mysqli_query($con,"delete from member where id='$id'");
// if ($data) { // Your condition
// This is where you would check if the query passed
// and send back the appropriate message.
if ($id) {
echo json_encode($id);
}
else {
echo http_response_code(500);
}
}
else {
echo "You don't belong here!";
}
you should use what is called JSON ( Javascript Object Notation, I think). This will let you order your data better to do that you have to use, json_encode.
Now I am not exactly sure what you mean by this id value from index.php
But taking your index.php file, I would change it like this
//make sure the is no space here
<?php
//start output buffering
ob_start();
$html = ['<div id="delMsg"></div>'];
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"select * from member");
$col=mysqli_num_fields($data);
$html[] = "<table>";
while($row=mysqli_fetch_array($data))
{
$html[] = "<tr>";
for($i=0;$i<$col;$i++)
{
$html[] = "<td>".$row[$i]."</td>";
}
$html[] = "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
$html[] = "</tr>";
}
$html[] = "</table>";
$result = [
'html' => implode("\n", $html),
'debug' => ob_get_clean()
];
header("Content-type:application/json");
echo json_encode($result);
//?> ending tags are undesirable
Your JavaScript part will change too
$(document).ready(function(){
$(".del").click(function(event){
event.preventDefault();
$.ajax({
url:"delete.php",
method:"get",
data:{id:'ID'},
dataType:"html",
success:function(data){
$('#delMsg').html(data.html);
}
})
})
})
You can see now that instead of just returning HTML, We will be returning it like this data in the Javascript and $result in php
{
html : '<div id=" ...',
debug : ""
}
I added ob_start and ob_get_clean this can be helpful because you cannot just echo content when outputting JSON, so this will catch any echo or print_r type content and put that into the debug item in the return.
Just replace
echo "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
To
echo "<td><a onclick="deleteRow($row[0])">Delete</a></td>";
Javascript
function deleteRow(recordID)
{
event.preventDefault();
$.ajax({
type: "GET",
url: "delete.php",
data:{id: recordID}
}).done(function( result ) {
alert(result);
});
}
In your PHP I recommend you to use PDO which is more easy and protected from SQL injection attacks.
PHP:
$db = new PDO('mysql:host=localhost;dbname=yourDB','root','');
$query = $db->prepare("Delete From yourTableName Where ID=:ID");
$id=$_GET['id'];
$query->bindParam('ID', $id);
$query->execute();
if ($query->rowCount()) {
echo "success";
}
else
{
echo "fails";
}

PHP multiple select - option data sending with ajax [duplicate]

This question already has answers here:
jquery serialize and multi select dropdown
(6 answers)
Get the values of 2 HTML input tags having the same name using PHP
(4 answers)
Closed 6 years ago.
I want to change the status in the database, with a select dropdown field.
I am sending with ajax. The first row is always working, but with multiple data i cant update the second, third..etc
I tried with serialize(), but its not working.
select from database:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".allbooks").change(function(){
var allbooks = $(this).val();
var dataString = "allbooks="+allbooks;
$.ajax({
type: "POST",
data: dataString,
url: "get-data.php",
success: function(result){
$("#show").html(result);
}
});
});
});
</script>
</head>
<body>
<?php
define("HOST","localhost");
define("USER","root");
define("PASSWORD","");
define("DATABASE","hotel");
$euConn = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
$selectRooms = "SELECT * FROM proba WHERE status='inRoom'";
$resultRooms = mysqli_query($euConn,$selectRooms);
if (mysqli_num_rows($resultRooms) > 0) {
echo "<div id='reserved' align='center'>";
While ($row = mysqli_fetch_array($resultRooms)) {
echo $row[1];
echo $row[0];
?>
<select name="allbooks" id="allbooks">
<option name="years">Choose</option>
<?php
for($i=1; $i<=19; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
</select><br />
<?php }
}
else
echo "<h4>nothing in the db</h4></div>";
?>
<div id="show">
</div>
</body>
</html>
and getting the results:
if(!empty($_POST["allbooks"])) {
var_dump($_POST);
$id = 2;
//echo $_POST['modelS'];
$room = $_POST['allbooks'];
$sql2 = "UPDATE proba SET room='$room' WHERE id_reservation='$id'";
$query = mysqli_query($euConn, $sql2);
var_dump($query);
}
How to change, or what would be a simple solution? Thanks for the help.
You have multiple select elements on the rendered page with the id allbooks That's wrong, IDs must be unique. You'll want to change those to a class and use $(".allbooks").change(function(){ ....
As far as sending the row id to the server with the update, you'll need to first add the row id to the select box so you can retrieve it later, something like '<select name="allbooks" class="allbooks" data-row-id="' . $row['id_reservation'] . '"> would work.
I would also recommend splitting the work up into several functions to better organize your code (classes would be even better)
It's hard to test without access to the DB, but this should do it for you. Note that I have the update function on the same page and updated the ajax url property to '' which will send the data to a new instance of the current page to handle the update.
<?php
require_once ("db_config.php");
function updateRoom($euConn, $newRoomVal, $id)
{
$stmt = $euConn->prepare("UPDATE proba SET room=? WHERE id_reservation=?");
$stmt->bind_param('ii', $newRoomVal, $id);
/* execute prepared statement */
$stmt->execute();
/* close statement and connection */
$affectedRows = mysqli_stmt_affected_rows($stmt) > 0;
$stmt->close();
return $affectedRows;
}
function getRooms($euConn)
{
$selectRooms = "SELECT * FROM proba WHERE status='inRoom'";
$resultRooms = mysqli_query($euConn,$selectRooms);
$rows = mysqli_fetch_all($resultRooms,MYSQLI_ASSOC);
return count($rows) < 1 ? '<h4>nothing in the db</h4></div>' : createSections($rows);
}
function createSections($rows)
{
$sections = [];
foreach( $rows as $row){
$options = [];
for ($i = 1; $i <= 19; $i++)
$options[] = "<option value=" . $i . ">" . $i . "</option>";
$options = implode('', $options);
$select = '<select name="allbooks" class="allbooks" data-row-id="' . $row['id_reservation'] . '"><option value="">Choose</option>' . $options . '</select><br/>';
// .. build all your other row elements here....
$section = 'some other compiled html'.$select;
$sections[]=$section;
}
return implode('', $sections);
}
$euConn = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
if(isset($_POST["allbooks"]) && $_POST["allbooks"] !='') {
$updated = updateRoom($euConn,$_POST["allbooks"],$_POST["rowId"] );
echo json_encode(['success'=>$updated]);
exit;
}
$pageSections = getRooms($euConn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".allbooks").change(function(){
var $this = $(this);
var allbooks = $this.val();
var rowId = $this.data('row-id');
var dataString = "allbooks="+allbooks+'&rowId='+rowId;
$.ajax({
type: "POST",
data: dataString,
url: "",
success: function(result){
$("#show").html(result);
}
});
});
});
</script>
</head>
<body>
<div id='reserved' align='center'>
<?php echo $pageSections ?>
<div id="show">
</div>
</body>
</html>

Interaction between jquery,MySQL and PHP to retrieve the result

I have two file, test.html & test.php. I would like to display the result of an SQL query via jQuery AJAX.
test.php outputs proper JSON, but I'm not able fetch the same on clicking upon the button "Fetch Data". Is it wrong way of using AJAX?
Once fetching the data in test.html, how do I access the contents?
test.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$ajax({
url:'test.php',
type:'get',
dataType:'json',
success:function(data){
alert(data);
console.log(data['success']);
console.log(data.success);
}
});
});
});
</script>
</head>
<body>
<button>Fetch Data</button>
</body>
</html>
test.php
<?php
$dbuser="root";
$dbname="test";
$dbpass="root";
$dbserver="localhost";
// Make a MySQL Connection
$con = mysql_connect($dbserver, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
// Create a Query
$sql_query = "SELECT ID, UserName, Status FROM user_details1";
// Execute query
$result = mysql_query($sql_query) or die(mysql_error());
$jsonArray = array();
while ($row = mysql_fetch_array($result)){
$jsonArrayItem = array();
$jsonArrayItem["ID"] = $row["ID"];
$jsonArrayItem["UserName"] = $row["UserName"];
$jsonArrayItem["Status"] = $row["Status"];
array_push($jsonArray, $jsonArrayItem);
//echo '<option value='. $row['id'] . '>'. $row['login'] . '</option>';
}
mysql_close($con);
$tableData = array(
"data" => $jsonArray
);
header('Content-Type: application/json');
echo json_encode($tableData,JSON_UNESCAPED_SLASHES);
die();
?>
How do I display/access/print the fetched result contents (AJAX section)?
Make a function like this
var dataToSend = "My Data";
$(button).on("click",function(event){
$.ajax({
method: "POST",
url: "test.php",
data: { pDataToSend: dataToSend }
}).done(function( data ) {
$('.results').empty();
$('.results').append(data);
});
});
And make a div like this
<div class="results></div>
In your PHP file you can read the POST using this code.
$foo = $_POST['pDataToSend'];
Also, your test.php file is all over the place. Use a PDO like this
//connect and setup database example
try {
$db = new PDO("mysql:host=localhost;dbname=second;port=8889","root","root");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e){
echo 'Could not connect to the database.105';
exit();
}
//select,insert,delete, update from database example
try{
$results = $db->prepare("SELECT * FROM articles WHERE article_id = ? AND user_id = ?");
$results->bindParam(1,$var);
$results->bindParam(2,$var2);
$results->execute();
$hold = $results->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit();
}

Issues with long polling and sessions (chat)

I made a friends chat that uses textfiles to store data and it all works more or less except when I sign in and write something to someone, nothing pops up (but the text is stored in the appropriate text file), then when I refresh the page it is ok from THEN ON, but on the other browser as the other user I have to also refresh the page in order for it to work normally both ways.
Basically, every time I log in I have to click the name of the person I want to chat with, then a window pops out and THEN i have to refresh or else it doen\sn't work.
I guess I have to kind of refresh the page whenever I click on a friend and want to chat with him and that it is a session problem.
here is home.php (users are redirected here when they log in on index.php page)
<?php
session_start();
if (!isset($_SESSION['user'])) {
header("Location: index.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">#import 'custom_chat.css';</style>
</head>
<body>
<h2>Hello, <?php echo $_SESSION['user']; ?></h2>
<hr>
<p><b>CONTACTS:</b></p>
<?php
require_once 'dbc.php';
$u = $_SESSION['user'];
$q = "SELECT user_id FROM users WHERE username='$u'";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
// current user id
$uid = $row[0];
$q = "SELECT u.username FROM users AS u, friends AS f
WHERE (f.f1 = '$uid' OR f.f2 = '$uid') AND (f.f1 = u.user_id OR f.f2 = u.user_id) AND (u.username != '$u')";
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_assoc($r)) {
echo '<div class=chat_contacts>';
echo '<div class='.$row['username'].'>';
echo '<div class=inner>';
echo '<div class=inner_chat></div>';
echo '<form>
<textarea class=chat_text></textarea>
</form>
';
echo '</div>'; // end .inner
echo '<a href="#" class='. $row['username'] .'>'.$row['username'] .'</a>
</div>';
echo '</div>'; // end .chat_contacts
}
?>
<p>HOME</p>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript">
var nc = '<?php echo $u ?>';
// toggle chat window
$('.chat_contacts a').click(function() {
$(this).prev('div.inner').toggle();
var tc = $(this).attr('class');
$(this).parent().parent().addClass(nc+tc);
$('textarea').focus(); // MD maybe
return false;
});
// call main chat function
$(function () {
updateChat();
}); // end ready
//update on enter
$('textarea.chat_text').keypress(function(e) {
$this = $(this); // textarea
if (e.which == '13') {
insertChat();
return false;
}
});
function insertChat() {
var text = $this.val();
$this.val('');
var ru = $this.parent().parent().parent().attr('class');
$.post('insert.php',{text:text, ru:ru}, function(data) {
if (data) {
alert(data)
}
});
}
var timestamp = 0;
function updateChat() {
$.ajax({
type: 'GET',
url: 'update.php?timestamp=' + timestamp,
async: true,
cache: false,
success:function(data) {
// alert(data);
var json = eval('('+data+')');
// if (json['msg'] != null) {
$('.chat_contacts.'+nc+json['nru']+' .inner_chat').append('<p>'+json['msg']+'</p>'); // MD
// }
timestamp = json['timestamp'];
setTimeout('updateChat()', 1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// alert('error '+textStatus+'('+errorThrown+')');
setTimeout('updateChat()', 1000);
}
});
}
</script>
</body>
</html>
update.php
<?php
session_start();
require_once('dbc.php');
error_reporting(E_ALL ^ E_NOTICE);
set_time_limit(0);
$ou = $_SESSION['user'];
$ru = $_SESSION['ru'];
session_write_close();
$q = "SELECT * FROM chats WHERE
(chats.f1='$ru' AND chats.f2='$ou') OR (chats.f1='$ou' AND chats.f2='$ru') ORDER BY time DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
// $filename = 'vojaolja.txt';
$q = "SELECT user_id FROM users WHERE username='$ou'
ORDER BY user_id DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
$fu = $row[0];
$q = "SELECT user_id FROM users WHERE username='$ru' ORDER BY user_id DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
$su = $row[0];
$q = "SELECT username FROM users WHERE username='$ru' ORDER BY user_id DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
$nru = $row[0];
if ($fu < $su) {
$filename = $fu.$su.'.txt';
} else {
$filename = $su.$fu.'.txt';
}
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif = filemtime($filename);
}
$response = array();
$data = file($filename);
$line = $data[count($data)-1];
$response['msg'] = $line;
$response['nru'] = $nru;
$response['timestamp'] = $currentmodif;
echo json_encode($response);
?>
Also, if someone wants to reproduce this on their own computer, I can post all the code here, it is just a few pages, it can be setup together with the database in literally 2 minutes.
EDIT:
as soon as I login, i see the following in the console:
http://localhost/x_super_chat/update.php?timestamp=0&_=1374509358392 (plus the rolling thingy, it is waiting)
Then i click on a friend's name, window pops up, I write something and i get this in the console:
http://localhost/x_super_chat/insert.php
AND THEN WHEN I REFRESH AGAIN (when it actually starts working) I get the following in the console.
http://localhost/x_super_chat/update.php?timestamp=0&_=1374509491493
http://localhost/x_super_chat/update.php?timestamp=1374509435&_=1374509493231 + the waiting thingy icon, it is waiting
So it changes after refresh, I need what I get after refresh to be there as soon as I log in.
EDIT 2: (after Pitchinnate's answer)
As soon as I login, I see this in the console:
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566749185 (plus the waiting animation)
Then I write something to the other person (say John), and I get the following:
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566749185
http://localhost/x_super_chat/insert.php
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566817682
http://localhost/x_super_chat/update.php?timestamp=1374565160&_=1374566817740
http://localhost/x_super_chat/update.php?timestamp=1374566817&_=1374566817801 (plus waiting animation)
THEN when I write something on the other side as John, I get the following: (this is from chrome so it is not the same as the console in firebug):
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566987051
http://localhost/x_super_chat/insert.php
http://localhost/x_super_chat/update.php?timestamp=1374566995&_=1374567004175
http://localhost/x_super_chat/update.php?timestamp=1374567004&_=1374567004215
One thing you can try is cancelling your long poll upon insert, create a global javascript variable outside your update function var myajax;
myajax = $.ajax({
type: 'GET',
url: 'update.php?timestamp=' + timestamp,
Then on insert:
function insertChat() {
myajax.abort();
var text = $this.val();
$this.val('');
var ru = $this.parent().parent().parent().attr('class');
$.post('insert.php',{text:text, ru:ru}, function(data) {
if (data) {
updateChat();
}
});
}

Categories