homepage Welcome to WebmasterWorld Guest from 54.242.140.11
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
jQuery JSON headache
I can see my variable, but I dont know how to alert it
allagents



 
Msg#: 4364371 posted 6:32 pm on Sep 19, 2011 (gmt 0)

Take a typical json..
the google maps api for instance


im trying to run this:

$.get('/properties/get-coordinates/address/<?php print $address;?> ',function(data){
$('#debug').html(data);
alert(data);

});


my debug div then displays the json:

{ "results" : [ { "address_components" : [ { "long_name" : "49", "short_name" : "49", "types" : [ "street_number" ] }, { "long_name" : "Saucel Hill Terrace", "short_name" : "Saucel Hill Terrace", "types" : [ "route" ] }, { "long_name" : "Paisley", "short_name" : "Paisley", "types" : [ "locality", "political" ] }, { "long_name" : "Renfrewshire", "short_name" : "Renfrewshire", "types" : [ "administrative_area_level_3", "political" ] }, { "long_name" : "Renfrewshire", "short_name" : "Renfrewshire", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "Scotland", "short_name" : "Scotland", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "United Kingdom", "short_name" : "GB", "types" : [ "country", "political" ] }, { "long_name" : "PA2 6", "short_name" : "PA2 6", "types" : [ "postal_code_prefix", "postal_code" ] } ], "formatted_address" : "49 Saucel Hill Terrace, Paisley, Renfrewshire PA2 6, UK", "geometry" : { "bounds" : { "northeast" : { "lat" : 55.8379530, "lng" : -4.417937999999999 }, "southwest" : { "lat" : 55.8363920, "lng" : -4.4212770 } }, "location" : { "lat" : 55.83792170, "lng" : -4.421174000000001 }, "location_type" : "RANGE_INTERPOLATED", "viewport" : { "northeast" : { "lat" : 55.83852148029150, "lng" : -4.417937999999999 }, "southwest" : { "lat" : 55.83582351970850, "lng" : -4.4212770 } } }, "partial_match" : true, "types" : [ "street_address" ] }, { "address_components" : [ { "long_name" : "Saucel St", "short_name" : "Saucel St", "types" : [ "route" ] }, { "long_name" : "Paisley", "short_name" : "Paisley", "types" : [ "locality", "political" ] }, { "long_name" : "Renfrewshire", "short_name" : "Renfrewshire", "types" : [ "administrative_area_level_3", "political" ] }, { "long_name" : "Renfrewshire", "short_name" : "Renfrewshire", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "Scotland", "short_name" : "Scotland", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "United Kingdom", "short_name" : "GB", "types" : [ "country", "political" ] }, { "long_name" : "PA1 1", "short_name" : "PA1 1", "types" : [ "postal_code_prefix", "postal_code" ] } ], "formatted_address" : "Saucel St, Paisley, Renfrewshire PA1 1, UK", "geometry" : { "bounds" : { "northeast" : { "lat" : 55.8419450, "lng" : -4.4198480 }, "southwest" : { "lat" : 55.8407950, "lng" : -4.4216290 } }, "location" : { "lat" : 55.84183299999999, "lng" : -4.4200330 }, "location_type" : "GEOMETRIC_CENTER", "viewport" : { "northeast" : { "lat" : 55.84271898029149, "lng" : -4.419389519708498 }, "southwest" : { "lat" : 55.84002101970850, "lng" : -4.422087480291503 } } }, "partial_match" : true, "types" : [ "route" ] } ], "status" : "OK" }



I'm trying to alert out this part:
"location" : { "lat" : 55.84183299999999, "lng" : -4.4200330 }

or even more specifically just get the lat and lng


simple enough?

 

astupidname

5+ Year Member



 
Msg#: 4364371 posted 10:47 am on Sep 21, 2011 (gmt 0)

Hi there, allagents, and welcome to webmasterworld!
my debug div then displays the json:

O.k, first problem here is that the json is a string which needs to be converted into an object to be more useful within the javascript. JSON.parse() is good for this, but only the more modern browsers support the JSON Native object and a seperate file -> https://raw.github.com/douglascrockford/JSON-js/master/json2.js is needed to have older browsers support the JSON global object. And even the JSON global object is not longer fully recommended for parsing json strings due to it's reliance upon the eval() function. That is, at least when the json text may be coming from an untrusted source (not your server). The latest function for parsing json is json_parse() -> https://raw.github.com/douglascrockford/JSON-js/master/json_parse.js which is considered safer though may be slightly slower. You should download that file and use json_parse() to convert json strings into actual objects.
The response ('data' after being converted to jsonObj below via parse_json(data)) here has two properties in this case "status" who's value is a string: "OK" <-provided all went well, and "results" who's value is an array and actually has two items - both are objects, but I'll assume here the second one is the one you want, base on the lat and lng you posted, so something along these lines should work out:
First include a script tag to parse_json.js:
<script type="text/javascript" src="json_parse.js"></script>

Then in a script which is below that set of tags, within your code:
$.get(
'/properties/get-coordinates/address/<?php print $address;?> ',
function (data) {
var location, lat, lng,
jsonObj = null;
//handle errant response possiblities
try {
jsonObj = json_parse(data);
} catch(er) {
alert(er.message);
}
if (typeof jsonObj == 'object' && jsonObj !== null && jsonObj.status == 'OK') {//all went well above
location = jsonObj.results[1].geometry.location; //results[1] is the second item, change to [0] if want first one
lat = location.lat;
lng = location.lng;
alert('lat: '+ lat +'\nlng: '+ lng);
}
}
);

If anybody's wondering, how to post formatted code on webmasterworld [webmasterworld.com]
Do not copy formatted code on webmasterworld from IE, use other browser such as Firefox.


Also, was just wondering, you know you could just hit googles Geocoding api from the client side instead of doing that from the server, right? Or are these cached results on the server? Just curious why the ajax and the google results coming from your own server.

astupidname

5+ Year Member



 
Msg#: 4364371 posted 11:00 am on Sep 21, 2011 (gmt 0)

Oh by the way, I sort of oopsed by forgetting that jquery has a parseJSON [api.jquery.com] method you could use instead, but be advised:
Where the browser provides a native implementation of JSON.parse, jQuery uses it to parse the string.
which means it will be using eval() I believe.
allagents



 
Msg#: 4364371 posted 8:56 am on Sep 22, 2011 (gmt 0)

lol thanks for your help! to answer your question, i use a php curl request to get the google data as a proxy because apparently jquery (or google or something) doesn't like when its coming from a different server :-s

that is very useful information so thanks! I fixed it (kind of) by making it a php array, and just sending co-ordinates x,y back rather than the full json, and splitting the string in javascript by comma!

not ideal but your reply will certainly come in useful!
Cheers!
Derek

astupidname

5+ Year Member



 
Msg#: 4364371 posted 11:06 am on Sep 22, 2011 (gmt 0)

lol thanks for your help! to answer your question, i use a php curl request to get the google data as a proxy because apparently jquery (or google or something) doesn't like when its coming from a different server :-s

Well, I figure the reason you had that problem is because you were maybe trying to use ajax to access the Google Geocoding api [code.google.com], and maybe you never looked at the Google Maps Javascript API V3 Services [code.google.com] which includes examples of how to incorporate google.maps.Geocoder [code.google.com] into a map, all from the client side, which you may find useful.

allagents



 
Msg#: 4364371 posted 1:04 pm on Sep 22, 2011 (gmt 0)

possibly, ive been tinkering with this stuff only for the last day or so, i dont really know lol, heres the php stuff:

//
// Create a cURL request to Google Maps
//
Zend_Layout::getMvcInstance()->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$add = str_replace(' ', '+',$this->getRequest()->getParam('address'));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=' . $add.'+UK');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($ch);
curl_close($ch);
$ob = json_decode($result, true);
echo $ob['results'][0]['geometry']['location']['lat'].','.$ob['results'][0]['geometry']['location']['lng'];

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved