0

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
2

3 Answers 3

2

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
1
  • You might want to switch your code around a bit, you are logging your latitude after your longitude, and the other way around Commented Nov 13, 2014 at 10:27
1

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
0

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.

answered Nov 13, 2014 at 10:23

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.