PDA

View Full Version : Accessing json object properties



CrazyCrisUk
Jun 7th, 2012, 09:55 AM
I'm making an ajax function. I'm having problems reading/accessing the returned json data.

The php handler returns the information as json.


// Get the route id.
if (is_numeric($_REQUEST['id']) == true) $route_id = $_REQUEST['id'];

// Access the database.
$sql = "SELECT * FROM routes WHERE id = :id";
$sth = $dbh->prepare($sql);
$sth->execute(array(':id' => $route_id));
$route = $sth->fetch(PDO::FETCH_ASSOC);

// JSON encode and print the results.
$json_route = json_encode($route);
echo ($json_route);


I'm using jquery, here is the ajax call.


$.ajax({
type: 'GET',
url: 'getroute.php',
dataType: 'json',
data: {
id : id
},
success: function(data) {
console.log(data);
var route = $.parseJSON(data);
},
error: function(jqXHR, textStatus) {
alert('Error:'+textStatus);
},
});


The cosole.log entry looks like such

Object { id="2", origin="northampton", destination="cardiff", more...}

My question is how can I access the data? I don't know to much js and I've tried the obvious ways.

route.origin comes back as being undefined even though it looks to me like I've set it???

Any Help?!??!

Thanks

Krupski
Jun 7th, 2012, 01:12 PM
I'm making an ajax function. I'm having problems reading/accessing the returned json data.




var object = {
'name' : 'Roger',
'age' : 'Too Old',
'height' : '72'
};

var str = '';

for (var x in object) {
str += x + ', ' + object[x] + '\n';
}

alert(str);
Hopefully this helps......


Additional info:

alert(object['name']); prints "Roger"

object['last_name'] = "Krupski"; adds to the object

object['height'] = 74; makes me taller :)

rnd me
Jun 8th, 2012, 02:46 AM
it's simply data.origin; you don't need to parse it when you use a json-type request.