0

How can I get the array data from a JSON sent back by my php script?

PHP code:

<?php
//connects to database
include 'connect.php';
$callback = $_GET['callback'];

$query = mysql_query("SELECT * FROM users");
$rows = array();
while($r = mysql_fetch_assoc($query)) {
   $rows[] = $r;
}

$out_string = json_encode($rows);

print $callback.'('.$out_string.');';
?>

The php code above puts all of user table's rows into an array and JSONencodes it. It is then sent back to this script:

$.getJSON(domain_path + 'generate.php?table=' +  tbname + '&callback=?', function(data) {
});

How can I display each row from the JSON array sent back?

For example the data will be sent back is:

([{"name":"user1","link":"google.com","approve":"true"},{"name":"user2","link":"yahoo.com","approve":"true"},{"name":"user3","link":"wikipedia.com","approve":"true"}]);

How would I use javascript (jQuery) to display it out like this:

Name: User1 , Link: google.com , Approve:True
Name: User2 , Link: yahoo.com , Approve:True
Name: User3 , Link: wikipedia.com , Approve:True

3 Answers 3

1

When you done print $callback.'('.$out_string.');'; you've ruined JSON formatted string. Send back in array instead then loop on through your rows and display data.

$out_string = json_encode(array('callback' => $callback, 'rows' => $rows));
Sign up to request clarification or add additional context in comments.

1 Comment

If the OP is using JSONP for a cross-domain AJAX call vi jQuery, his original print line was correct. I had to use exactly the same formatting yesterday to achieve a cross domain call
0

You should do

function(data) {
    $.each(data, function(){
        $('#result').append('<p>Name:'+this.name+' Link:'+this.link+' Approve'+this.approve+'</p>');
    });
}

fiddle here http://jsfiddle.net/hUkWK/

Comments

0
$.getJSON(domain_path + 'generate.php?table=' +  tbname + '&callback=?', function(data) {
  $.each(data, function(i, item) {
    $("#mycontainer").append("<p>Name: " + item.name + "</p>");
    $("#mycontainer").append("<p>Link: " + item.link + "</p>");
  });
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.