2

So I have a database pass a whole bunch of data using PHP back to jQuery through JSON.. I'm trying to access individual columns from the returned data but no luck..

My PHP:

header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);

while($row = mysql_fetch_assoc($result)){ 
  $myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';

Here's my JS:

function getAll(){
    jQuery.ajax({
        url:'example.com/js/getAll.php',
        async: true,
        dataType: 'jsonp',
        success:function(data){
            $('.quoteList').append(data[0]);
        }
    });
}

Currently that appends the following to the element:

[{"id":"1","text":"The most wasted of all days is one without laughter.","author":"E.E. Cummings","status":"1"}]

So for example.. if I wanted the jQuery to go through data[0] to data[92] (the last one) and append the author of each to .quoteList, how could I do that? I've tried data[0][1] and data[0][author]

pashOCONNOR
  • 571
  • 2
  • 6
  • 15

5 Answers5

5

You can use $.each() to loop through the data and append the author:

$.each(data, function(i) {
    $('.quoteList').append(data[i]['author']);
});
Felix
  • 37,892
  • 8
  • 43
  • 55
  • It'll work for data[i] but doesn't pick up on the author part for some reason.. It does nothing when I add that. – pashOCONNOR Mar 28 '14 at 05:41
  • Where are you adding this code? It goes in `success: function(data){ ... HERE ... }` – Paul Mar 28 '14 at 05:52
  • That's exactly where I'm inserting it. – pashOCONNOR Mar 28 '14 at 05:57
  • Do you get any console messages? What happens if you `console.log(data)` in the success function? – Paul Mar 28 '14 at 06:03
  • @pashOCONNOR Make sure that your JSON response is correctly structured and no syntax error. Please check your browser console for debugging as well. – Felix Mar 28 '14 at 06:06
  • 1
    @Felix I think the PHP is defective. It seems to JSON encode each row and sends that inside `callback()` double JSON encoded. That's going to convert some objects to strings, have escaped quotes, and other steps that seem unnecessary. Not sure if that is correct, or exactly what a JSONP response should look like. – Paul Mar 28 '14 at 06:14
  • ^Paul & Felix's solutions together worked perfect. Thank you both! – pashOCONNOR Mar 29 '14 at 07:29
2

The PHP might be defective because json_encode is called twice, and this is unusual. As written this would be flattening the rows into JSON strings, but mere strings nonetheless, which then get JSON encoded again into an array of strings. This is probably not what you intended, as it would be making it possible to print the received data but not access the components of rows which will be decoded to strings and not objects.

Compare https://stackoverflow.com/a/6809069/103081 -- here the PHP echoes back a callback with a single JSON object inside parenthesis ().

I suspect the fix looks like https://stackoverflow.com/a/15511447/103081 and can be adapted as follows:

header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);

while($row = mysql_fetch_assoc($result)){ 
  $myjsons[] = $row;
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';

Once you have this, you should be getting back proper JSON for your array of objects and be able to use @Felix's code on the client side.

Community
  • 1
  • 1
Paul
  • 26,170
  • 12
  • 85
  • 119
0

you need to use loop on your data, try this

success:function(data){
    for (var i in data) {
        $('.quoteList').append(data[i]);
    }
}
zzlalani
  • 22,960
  • 16
  • 44
  • 73
0

This should work: (upd. all code:)

function getAll(){
    jQuery.ajax({
        url:'example.com/js/getAll.php',
        async: true,
        dataType: 'jsonp',
        contentType: "application/json",
        success:function(data){
            var str = "";

            $(data).each(function(index, item){
                str += item.author + "  ";
            });

            $('.quoteList').append(str);
        }
    });
}
ka3yc
  • 116
  • 4
  • 1
    unfortunately it returns a bunch of "undefined" over and over :( – pashOCONNOR Mar 28 '14 at 05:45
  • try pls this option of $.ajax: contentType: "application/json" – ka3yc Mar 28 '14 at 05:51
  • and also, if "data" comes as "string", you may need to parse this in a json. I use [json2.js]:(http://code.ohloh.net/file?fid=6zoZlEsxuWphE-W_4_Psb9cBh9U&cid=IE7HnizPlgE&s=&fp=289108&mp=&projSelected=true#L0) library for this: json.parse(data); //then processing data as array – ka3yc Mar 28 '14 at 06:38
0

Your problem is here:

while($row = mysql_fetch_assoc($result)){ 
  $myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';

you need something like this:

while($row = mysql_fetch_assoc($result)){ 
  $myjsons[] = $row;
}
$myjsons['callback'] = $_GET['callback'];
echo json_encode($myjsons);
meda
  • 45,103
  • 14
  • 92
  • 122