Ceejay
Ceejay

Reputation: 7257

How to get json data in javascript

I am getting the values from database in php and encoded the retrieved values to json data format.

php code:

<?php
require_once('config.php');
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM theater';
mysql_select_db($dbname);
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_assoc($retval))
{
echo json_encode($row) "\r\n"; 
}
mysql_close($conn);
?>

output:

{"id":"11","region":"Central","cord_latitude":"12.9237","cord_longitude":"77.5535"}

now i need to get only some values from the json data to javascript. I need only cord_latitude and cord_longitude values in javascript how can i get those values in javascript?

Upvotes: 0

Views: 326

Answers (3)

Geert
Geert

Reputation: 1227

Change:

echo json_encode($row) "\r\n"; 

To:

echo json_encode(array("cord_latitude" => $row["cord_latitude"], "cord_longitude" => $row["cord_longitude"]));

And then use JSON.parse();:

json = 'YOUR JSON STRING'
theater = JSON.parse(json);

console.log('Longitude: ' + theater.cord_longitude)
console.log('Latitude: ' + theater.cord_latitude)

This way only those 2 fields will go over the line, resulting in less trafic and thus faster loading.

Upvotes: 0

SubjectCurio
SubjectCurio

Reputation: 4872

You can use JSON.parse(), for example

<script type="text/javascript">
    var json_data = '{"id":"11","region":"Central","cord_latitude":"12.9237","cord_longitude":"77.5535"}';
    var parsed_data = JSON.parse(json_data);

    console.log('long: ' + parsed_data.cord_longitude)
    console.log('lat: ' + parsed_data.cord_latitude)
</script>

Upvotes: 2

Rutunj sheladiya
Rutunj sheladiya

Reputation: 646

Parse your json encoded string in javascript:

var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );

Upvotes: 1

Related Questions