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?

CJAY
  • 6,989
  • 18
  • 64
  • 106
  • Have a look at: http://stackoverflow.com/questions/4935632/parse-json-in-javascript –  Nov 13 '14 at 10:16
  • Get JSon using PHP URL and parse it http://stackoverflow.com/questions/9922101/get-json-data-from-external-url-and-display-it-in-a-div-as-plain-text – Amy Nov 13 '14 at 10:17

3 Answers3

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>
SubjectCurio
  • 4,702
  • 3
  • 32
  • 46
  • You might want to switch your code around a bit, you are logging your latitude after your longitude, and the other way around – Geert Nov 13 '14 at 10:27
1

Parse your json encoded string in javascript:

var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );
Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
Rutunj sheladiya
  • 629
  • 7
  • 21
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.

Geert
  • 1,217
  • 8
  • 20