Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Patrick Koch
Patrick Koch
40,501 Points

AJAX and PHP arrays

I have a messages.php where I load all the data base messages with mysql-fetch, and have different function to certain messages, like:

get_messages_all()
get_messages_recent()
....

the both return arrays Now I wanted to load that messages per ajax, and I am kind of stuck, I know i can encode the arrays like

echo json_encode(get_messages_all())

to get json arrays and I can echo out the json array. It works. but I don't know how to integrate my messages.php into the ajax request.

$(document).ready(function () {
  $.getJSON('messages.php', function (data) {
    var statusHTML = '<ul>';
    $.each(data,function (index, message) {
        statusHTML +='<li class="in">' + message.name + '</li>';
    });
    statusHTML += '</ul>';
    $('#output').html(statusHTML)
  }); // end getJSON
});

Hope I explained my problem good enough. greetings Patrick

Dave McFarland
Dave McFarland
Treehouse Teacher

If you just load the messages.php file in your browser, what does it look like? If you can paste the exact JSON string returned by the messages.php file, we could probably help you.

Patrick Koch
Patrick Koch
40,501 Points

Thanks for supporting. messages.php I just have php functions, that just give a return of the arrays, like

function get_messages_all(){
    require("dev-database.php");

    try{
        $results = $db->query("SELECT time, nick, message FROM inf");   
    }catch (Exception $e){
        echo "Data could not be retrieved from the database.";
        exit;
    }

    $messages = $results->fetchAll(PDO::FETCH_ASSOC);
    return $messages;
}

If I var_dump get_messages_all():

array(2) { [0]=> array(3) { ["time"]=> string(19) "2014-07-04 07:16:52" ["nick"]=> string(4) "Nick" ["message"]=> string(5) "Hello" } [1]=> array(3) { ["time"]=> string(19) "2014-07-04 07:16:52" ["nick"]=> string(6) "Felix " ["message"]=> string(12) "Hi, whats up" } } 

And If I var_dump the json encode get_messages_all_json():

string(136) "[{"time":"2014-07-04 07:16:52","nick":"Nick","message":"Hello"},{"time":"2014-07-04 07:16:52","nick":"Felix ","message":"Hi, whats up"}]"

Till know I worked with the messages.php file as model, and I don't know how or where to integrate the json encoding? also in same file? or a different one, whats the common practice?

3 Answers

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

Patrick Koch

You should send the JSON-encoded string as a response to the AJAX request. So when you use the $.getJSON() method and request messages.php you need to send back JSON.

The problem in your original jQuery code is that you're trying to access a property named name, but there isn't one in the JSON data. Instead you have a property named nick. This should work:

$(document).ready(function () {
  $.getJSON('messages.php', function (data) {
    var statusHTML = '<ul>';
    $.each(data,function (index, message) {
        statusHTML +='<li class="in">' + message.nick + '</li>';
    });
    statusHTML += '</ul>';
    $('#output').html(statusHTML)
  }); // end getJSON
});
Patrick Koch
Patrick Koch
40,501 Points

First of all, thanks Dave, I changed name with nick.... Still not working, If I just put

[{"time":"2014-07-04 07:16:52","nick":"Nick","message":"Hello"},{"time":"2014-07-04 07:16:52","nick":"Felix ","message":"Hi, whats up"}]

in my messages.php file the ajax request works, but if I write

<?php
function get_messages_all(){
    require("dev-database.php");
    try{
        $results = $db->query("SELECT time, nick, message FROM inf");   
    }catch (Exception $e){
        echo "Data could not be retrieved from the database.";
        exit;
    }
    $messages = $results->fetchAll(PDO::FETCH_ASSOC);
    return $messages;
}
function get_messages_all_json(){
    return json_encode(get_messages_all());
}
echo get_messages_all_json();

(its displaying the same json string in Browser if I open messages.php), but its not displaying with my ajax request

Dave McFarland
Dave McFarland
Treehouse Teacher

Have you looked at the JavaScript console in your browser to see if there are any errors? In Chrome, type Option-Cmd-J (mac) or Ctrl-Shift-J (windows) to open the console.

Patrick Koch
Patrick Koch
40,501 Points

°° the console is a good friend, safes me some weekends....No there are no errors,

I just bring it short up.. html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>OnlineChat</title>
  <link  rel="stylesheet" href="css/main.css" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <script src="js/widget.js"></script>
</head>
<body>
<!-- Output the data from db -->
<div id="output">


</div>
<!-- Input the data into the db -->
<div id="input">
  <form method="post" action="">
    <input type="text" name="nick" value="" readonly=""/>
    <button href="">refresh</button>
    <button href="">send</button></br>
    <textarea name="message"></textarea></br>
  </form>
</div>

</body>

</html>

the console shows me >>XHR finished loading: GET "http://localhost/projekte/chat/inc/messages.php" <<

the php for the ajax request messages.php

<?php
// get all messages in an array
function get_messages_all(){
    require("dev-database.php");

    try{
        $results = $db->query("SELECT time, nick, message FROM inf");   
    }catch (Exception $e){
        echo "Data could not be retrieved from the database.";
        exit;
    }

    $messages = $results->fetchAll(PDO::FETCH_ASSOC);
    return $messages;
}

function get_messages_all_json(){
    return json_encode(get_messages_all());

}

echo get_messages_all_json();

If I call this side in the browser it shows me:

[{"time":"2014-07-04 07:16:52","nick":"Nick","message":"Hello"},{"time":"2014-07-04 07:16:52","nick":"Felix ","message":"Hi, whats up"}]

the ajax request,

$(document).ready(function () {
  $.getJSON('inc/messages.php', function (data) {
    var statusHTML = '<ul>';
    $.each(data,function (index, message) {
        statusHTML +='<li>' + message.nick + '</li>';
    });
    statusHTML += '</ul>';
    $('#output').html(statusHTML)
  }); // end getJSON
});

the really ridicules for me is that, if I write the json string with hand its working.

thanks for don't giving up on me .-)

greetings Patrick