Postanowiłem w ramach ćwiczenia zrobić prosty czat oparty na PHP/MySQL/AJAX
Czat ma mieć możliwość wysyłania wiadomości i następnie ta wiadomość zostaje wyświetlona w okienku czatu bez przeładowania strony.
Wszystko jest okej, ale:
1. Gdy dodam:
wiadomość nr 1, otrzymuję (wiadomość nr 1)
wiadomość nr 2, otrzymuję (wiadomość nr 1,wiadomość nr 1, wiadomość nr 2)
wiadomość nr 2, otrzymuję (wiadomość nr 1,wiadomość nr 1, wiadomość nr 2,wiadomość nr 1,wiadomość nr 2, wiadomość nr 3)
itd.
czyli wiadomości się powtarzają( obrazek lepiej to wyjaśnia)

Uploaded with ImageShack.us
jak tego uniknąć ?
2. Załóżmy ze mamy 2 userów. Jeden wysyła wiadomość i mu się odświeża okno, a drugiemu nie. Jak to rozwiązać, że gdy ktoś wyśle wiadomość okno przeładuję się wszystkim.
index.php
<html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> </head> <body> <style> .chat { margin:0 auto; width:700px; height:600px; background-color:#e7e7e7; border: 1px #000 solid; font-family:verdana; font-size:11px; } .wall { width:660px; height:500px; margin: 20px; background-color:#ffffff; border: 1px #000 solid; } .row{ padding:10px 20px; } .row:nth-child(odd) { background-color:red; } .row:nth-child(even) { background-color:yellow; } float:left; } .mess{ display:inline-block; margin-left:20px; } .message { width:560px; height:30px; float:left; border:1px #000 solid; padding-left:3px; } .submit { display:inline-block; height:30px; border:1px #000 solid; cursor:pointer; width:80px; margin-left:20px; background-color:#707070; } .action{ width:660px; margin:20px; } </style> <div> <div class="chat"> <div class="wall"> </div> <div class="action"> <form class="form" method="post"> <input class="message" name="message" type="text"/> <input class="submit "type="submit"/> </form> </div> </div> </div> <script> $(document).ready(function(){ $('.form').submit(function(){ var message = $('.message').val(); $.ajax({ type: 'POST', url: 'sendmessage.php', dataType: 'json', data: { body: message, }, success:function(json){ //alert('pipka'); for(i=0; i<json.length; i++) { $('.wall').append('<div class="row"><div class="date">' +json[i]['date']+ '</div><div class="mess">'+json[i]['body']+'</div></div>'); } }, error: function() { alert('wystąpił błąd :)'); } }); return false; }); }); </script> </body> </html>
sendmessage.php
<?php /** * @author * @copyright 2013 */ //var_dump($_POST); try{ $pdo = new PDO('mysql:host=localhost;dbname=chat', 'root', ''); $pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare('INSERT INTO messages(body) VALUES(:body)'); $stmt->bindValue(':body', $_POST['body'],PDO::PARAM_STR); $stmt->execute(); $stmt = $pdo->prepare('SELECT * FROM messages LIMIT 50;'); $stmt->execute(); $messages=$stmt->fetchAll(); $stmt->closeCursor(); } catch(PDOException $e) { } ?>