0

The whole code works, but the problem appears when I'm trying to get data from the database:

img

For fetching data, I'm using PHP:

function chatStory() {
$sql = mysql_query("SELECT * FROM chat WHERE username = '".$_SESSION['username']."' ");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
  $rows[] = $r;
}
echo json_encode($rows);
}

Then I'm able to retrieve that data by JavaScript:

    $.ajax({                                      
  url: 'chat.php?action=chatstory', data: "", dataType: 'json',  success: function(rows)        
  {
    for (var i in rows)
    {
      var row = rows[i];          
      var msg = row[0];
      var user = row[1];
    $("#chat_"+nazwa+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+user+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+msg+'</span></div>');
    } 
  } 
});

I can't find my error. Every message is showing. There are 7 messages in the database and I can see 7 messages in the chatbox, but they are appearing as undefined.

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
xLeviGames
  • 31
  • 4
  • 2
    ***Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php).*** [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Mar 08 '17 at 21:31
  • [Have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there any errors reported? Are you running this on a web-server?](http://jayblanchard.net/basics_of_jquery_ajax.html) – Jay Blanchard Mar 08 '17 at 21:31
  • Yes, I included jQuery, I don't get any errors and I'm running this once on web server and now on my computer with XAMPP. I have 1 record on dev console, but it is from another function. – xLeviGames Mar 08 '17 at 21:48
  • What do you get when you `console.log(rows);` in your success function? – Jay Blanchard Mar 08 '17 at 22:01
  • I have some arrays, for example Array[2]0: Objectmsg: "test"sendTo: "Janusz"username: "kasia"__proto__: Object1: Objectlength: 2 – xLeviGames Mar 09 '17 at 13:08
  • Problem was in var msg = row[0] etc., it should be var msg = row['mgs'] etc. Thanks for your help! :) – xLeviGames Mar 09 '17 at 17:08

0 Answers0