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?
asked Nov 13, 2014 at 10:14
-
Have a look at: stackoverflow.com/questions/4935632/parse-json-in-javascriptuser3849602– user38496022014年11月13日 10:16:27 +00:00Commented Nov 13, 2014 at 10:16
-
Get JSon using PHP URL and parse it stackoverflow.com/questions/9922101/…Amy– Amy2014年11月13日 10:17:29 +00:00Commented Nov 13, 2014 at 10:17
3 Answers 3
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>
answered Nov 13, 2014 at 10:20
-
You might want to switch your code around a bit, you are logging your latitude after your longitude, and the other way aroundGeert– Geert2014年11月13日 10:27:19 +00:00Commented Nov 13, 2014 at 10:27
Parse your json encoded string in javascript:
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );
Mariusz Jamro
31.8k25 gold badges129 silver badges170 bronze badges
answered Nov 13, 2014 at 10:20
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.
default