2016-06-15 6 views
0

Ich baue ein Chat-System. Ich sende eine AJAX-Anfrage nach alle 2 Sekunden, um neue Nachrichten zu erhalten. Jetzt ist das Problem, dass nach jeder 2 Sekunden Ajax-Aufruf neu laden Ich alle Nachrichten wieder vom Botschafts Tabelle statt Abrufen nur neue Nachricht ..Call Ajax nur wenn neue Zeile in PHP eingefügt Mysql

Was ich will, ist, dass, wenn Seite erstmals dann alle Nachrichten ist laden würde laden und dann danach einfach die neue Nachricht aus der Nachrichtentabelle laden, anstatt alle Nachrichten nach 2 Sekunden immer wieder abzurufen. Unten ist mein Code.

JQuery

$(document).ready(function(){ 

//get new message every 2 second 
var interval = setTimeout(function() { 

$("#chatting").load("get_message_ajax.php", {c_id:c_id, from_id:from_id, to_id:to_id}); 


}, 2000); 

}); 

PHP

if(isset($_POST['c_id'])){ 

$conversation_id = isset($_POST["c_id"]) ? trim(strip_tags($_POST["c_id"])) : ""; 
$from_id = isset($_POST["from_id"]) ? trim(strip_tags($_POST["from_id"])) : ""; 
$to_id = isset($_POST["to_id"]) ? trim(strip_tags($_POST["to_id"])) : ""; 


//fetch all the messages of $user_id(loggedin user) and $user_two from their conversation 

$stmt = $pdo->prepare("SELECT * FROM `messages` m WHERE conversation_id=:conversation_id"); 
$stmt->execute(array(":conversation_id"=>$conversation_id)); 
$m = $stmt->fetchAll(PDO::FETCH_ASSOC); 
} 

Bitte helfen Sie mir .. Vielen Dank im Voraus ..

Antwort

0

Versuchen Sie diese einfache und schnelle Lösung

$(document).ready(function(){ 

var chatData = ""; // default set emty 

//get new message every 2 second 
var interval = setTimeout(function() { 

    $.post("get_message_ajax.php", {c_id:c_id, from_id:from_id, to_id:to_id}) 
     .done(function(data) { 
      if(chatData !== data){ // if changes are exist in result then update 
       $("#chatting").html(data); 
      } 
      chatData = data; 
     } 
    }); 

}, 2000); 

}); 
+0

es alle 2 Sekunden Datenbank getroffen. nicht, wenn neue Zeile einfügen in db –

+0

das wäre hier Hilfe: [http://stackoverflow.com/questions/8100594/refresh-content-automatic-if-the-database-changes](http://stackoverflow.com/ Fragen/8100594/Aktualisieren-Inhalt-automatisch-wenn-die-Datenbank-Änderungen) –