First i want to thank you for reading this :).
Im creating a Live chat with PHP and jQuery. Yeah iknow what you'r thinking right now. USE SOCKET.IO. Iknow, and i want to. But first i want to create one with Ajax. So if you are gonna say use websockets or node.js or something it doesnt help me. I just want to fix this.
So my problem.
The chat data will be parsed in a json array on a file.
[{"id":"1","user_id":"2","user_clr":"red","message":"Test bericht","timestamp":"2017-03-09 16:04:34","username":"Vienna"},{"id":"2","user_id":"1","user_clr":"blue","message":"Test berciht 2","timestamp":"2017-03-09 16:04:32","username":"Chris"},{"id":"3","user_id":"2","user_clr":"red","message":"tst bericht 4","timestamp":"2017-03-09 16:04:35","username":"Vienna"},{"id":"4","user_id":"2","user_clr":"red","message":"test bericht 3","timestamp":"2017-03-09 16:04:36","username":"Vienna"},{"id":"5","user_id":null,"user_clr":"sda","message":null,"timestamp":null,"username":null},{"id":"6","user_id":"1","user_clr":"blue","message":"Test","timestamp":null,"username":"Chris"},{"id":"7","user_id":null,"user_clr":null,"message":null,"timestamp":null,"username":null},{"id":"8","user_id":null,"user_clr":null,"message":"TEST","timestamp":null,"username":"TEST"}]
Yes it is a valid JSON.
there are some nulls in it but it doesnt matter.
Im using at this moment this jQuery:
function loadChats(){
$.getJSON('/d.php', function(data) {
console.log(data.length + " keys loaded");
var strVar="";
$( "#view_ajax" ).empty();
$.each(data, function(index) {
strVar += "<div class=\"messenger-message-container\" style=\"color:white;\">";
strVar += " ";
strVar += " <div class=\"messages\">";
strVar += " <ul>";
strVar += " <li>";
strVar += "";
strVar += " <div class=\"message\"><font color=\"black\">";
strVar += "<\/font>";
strVar += " ";
strVar += " <div style=\"background-color:" + data[index].user_clr + ";\">";
strVar += data[index].username + ": " + data[index].message;
strVar += " <\/div>";
strVar += " <\/div>";
strVar += " <\/li>";
strVar += " <div class=\"time-ago\">1:26<\/div>";
strVar += " <\/ul>";
strVar += " <\/div>";
strVar += " ";
strVar += " <\/div>";
});
$('#view_ajax').append(strVar);
});
setTimeout("loadChats()", 1000);
}
loadChats();
Now it is refreshing the whole div. It emptys the html and put the html again into the strVar
, so new data will be included now either.
But what i really want is to load the chat when you open the chat page and then only check if theire is a new row in the database. If so, put a new div on the output page. So the olders message wouldt be loaded again.
How can i realize this?
I tried to read other ajax tutorials about data, but i cant find the right one which is cleared what i want.
----- Added PHP code for answer from: Guillaume STLR
<?php
require_once './core/init.php';
$toxDB = toxDB::getInstance();
$toxData = $toxDB->getAll('chats', 20);
print_r(json_encode($toxData->results()));
this query is running when running this function
object(PDOStatement)[4]
public 'queryString' => string 'SELECT * FROM chats LIMIT 20' (length=28)
and is printing the JSON which i mention above.
You can try to store locally which ids are already rendered :
function loadChats(){
$.getJSON('/d.php', function(data) {
console.log(data.length + " keys loaded");
var strVar="";
$.each(data, function(index) {
if(cacheId.indexOf(data[index].id) === -1) {
//Store to cache
cacheId.push(data[index].id);
strVar += "<div class=\"messenger-message-container\" style=\"color:white;\">";
strVar += " ";
strVar += " <div class=\"messages\">";
strVar += " <ul>";
strVar += " <li>";
strVar += "";
strVar += " <div class=\"message\"><font color=\"black\">";
strVar += "<\/font>";
strVar += " ";
strVar += " <div style=\"background-color:" + data[index].user_clr + ";\">";
strVar += data[index].username + ": " + data[index].message;
strVar += " <\/div>";
strVar += " <\/div>";
strVar += " <\/li>";
strVar += " <div class=\"time-ago\">1:26<\/div>";
strVar += " <\/ul>";
strVar += " <\/div>";
strVar += " ";
strVar += " <\/div>";
}
});
$('#view_ajax').append(strVar);
setTimeout("loadChats()", 1000);
});
}
//Add caching
var cacheId = [];
loadChats();
You can also filter your datas with backend by sending to server the last chat id value and filtering with this. Like this :
PHP :
$lastId = isset($_GET['last_id']) ? $_GET['last_id'] : null;
require_once './core/init.php';
$toxDB = toxDB::getInstance();
if($lastId) {
//Don't know how to filter with your model, but you get it.
$toxData = $toxDB->getAllBy('chats', 'WHERE ID > :ID', ['ID' => $lastId], 20);
}else {
$toxData = $toxDB->getAll('chats', 20);
}
print_r(json_encode($toxData->results()));
Javascript :
function loadChats() {
$.getJSON('/d.php?last_id=' + lastId, function(data) {
console.log(data.length + " keys loaded");
var strVar="";
$.each(data, function(index) {
//Set last chat id
lastId = data[index].id;
strVar += "<div class=\"messenger-message-container\" style=\"color:white;\">";
strVar += " ";
strVar += " <div class=\"messages\">";
strVar += " <ul>";
strVar += " <li>";
strVar += "";
strVar += " <div class=\"message\"><font color=\"black\">";
strVar += "<\/font>";
strVar += " ";
strVar += " <div style=\"background-color:" + data[index].user_clr + ";\">";
strVar += data[index].username + ": " + data[index].message;
strVar += " <\/div>";
strVar += " <\/div>";
strVar += " <\/li>";
strVar += " <div class=\"time-ago\">1:26<\/div>";
strVar += " <\/ul>";
strVar += " <\/div>";
strVar += " ";
strVar += " <\/div>";
});
$('#view_ajax').append(strVar);
});
setTimeout("loadChats()", 1000);
}
var lastId = null;
loadChats();
If you had to choose : Filtering is better. With your solution, every second you send unecessary (and potentially big) JSON to every clients connected to your page, even if the chat conversations are already rendered. With filtering you're saving bandwith and database operations by adding a WHERE filter.