Extract json array data using javascript - javascript

I would like to obtain the formatted_address from the json data returned from the following query string by using javascript.
http://maps.googleapis.com/maps/api/geocode/json?latlng=44.4647452,7.3553838&sensor=true
function getReverseGeocodingData(lat, lng) {
//use ajax and json
$.ajax({
type: "POST",
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng="+sessionStorage.latitude+","+sessionStorage.longitude+"&sensor=true",
data: jsondata,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var address = response.Result;
var error = response.Error;
if (address != null) {
alert("Found current location: " + address.formatted_address);
sessionStorage.currentAddress = address.formatted_address;
return;
}
},
error: function (msg) {
errorConnection();
}
});
}
I tried getting formatted_address but it return undefined.

You can get formatted address like this (Ajax Success)
success: function (results) {
var address = (results[0].formatted_address);
alert(JSON.stringify(address));
},

just changed the success function with this, you will get all the formatted address
success: function (response) {
var address = response.results;
var error = response.error; //write exact word of the "error" which you get in response
if(address.length > 0) {
for(i=0; i<address.length; i++) {
console.log("Found current location: " + address[i].formatted_address);
}
}
},

Sorry my previous response only fixed the AJAX request-
specifying contentType on a request is not required and has no impact - this is controlled by the server.
jQuery already will parse the request to an object, calling JSON.stringify on the response was causing the object to be parsed into a JSON formatted string, removing that line resolved the issue. Also specifying dataType didn't seem to be necessary.
It's worth noting that you're passing lat, and lng arguments to the function but not using them - I'd suggest either adding a lines like:
lat = lat || sessionStorage.latitude;
lng = lng || sessionStorage.longitude;
Below should be a solution complete with my suggestions:
function getReverseGeocodingData(lat, lng) {
lat = lat || sessionStorage.latitude;
lng = lng || sessionStorage.longitude;
jsondata = {};
//use ajax and json
$.ajax({
type: "POST",
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + sessionStorage.latitude + "," + sessionStorage.longitude + "&sensor=true",
data: jsondata,
success: function (response) {
var address = response.results[0].formatted_address;
var error = response.Error;
if (address != null) {
alert("Found current location: " + address);
sessionStorage.currentAddress = address;
}
},
error: function (msg) {
errorConnection();
}
});
}

There are a few things to fix:
apparently you don't have to post data as you're making a GET request.
I rewrote your code to take the parameters from lat and lng in order to test it easily.
response is an object that contains an array of results objects (lowercase r plural). Each object contains a formatted_address property.
Most likely you'll want to fetch the first one:
response.results[0].formatted_address
function getReverseGeocodingData(lat, lng) {
//use ajax and json
$.ajax(
{
type: "GET",
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true",
dataType: "json",
success: function (response) {
alert("Found current location: " + response.results[0].formatted_address);
},
error: function (msg) {
alert('error');
}
});
}
To try it:
getReverseGeocodingData(44.4647452,7.3553838);
Outputs:
Found current location: Via Pasubio, 34, 12025 Dronero CN, Italia

Related

How to read data using JSONP, Ajax and jquery?

I am trying to read data from this API, but it is not working, I have an input box where I enter the isbn number and then get the data, using jsonp. Could you possibly help me in identifying where my error("Cannot read property 'title' of undefined") is?
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(isbn){
var infoUrl = isbn.info_url;
var thumbnailUrl = isbn.thumbnail_url;
var title = isbn.details.title;
var publishers = isbn.details.publishers;
var isbn13 = isbn.details.isbn_13;
console.log(isbn.info_url);
}
});
}
Open Library's API expects bibkeys to be prefixed with their type and a colon, rather than just the number alone:
function add(){
var isbn = 'ISBN:' + $("#isbn").val();
// ...
The colon also means the value should be URL-encoded, which jQuery can do for you:
$.ajax({
url: "https://openlibrary.org/api/books?jscmd=details&callback=?",
data: { bidkeys: isbn },
dataType: "jsonp",
Then, the data it returns reuses the bibkeys you provided as properties:
{ "ISBN:0123456789": { "info_url": ..., "details": { ... }, ... } }
To access the book's information, you'll have to first access this property:
success: function(data){
var bookInfo = data[isbn];
console.log(bookInfo.details.title);
// etc.
}
Example: https://jsfiddle.net/3p6s7051/
You can also retrieve the bibkey from the object itself using Object.keys():
success: function (data) {
var bibkey = Object.keys(data)[0];
var bookInfo = data[bibkey];
console.log(bookInfo.details.title);
// ...
}
Note: You can use this to validate, since the request can be technically successful and not include any book information (i.e. no matches found):
success: function (data) {
var bibkeys = Object.keys(data);
if (bibkeys.length === 0)
return showError('No books were found with the ISBN provided.');
// ...
Example: https://jsfiddle.net/q0aqys87/
I asked a professor, and this is how she told me to solve it:
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(data){
var thumb=data["ISBN:"+isbn+""].thumbnail_url;
....
}
});
}

Google Maps Geocoding AJAX using a variable as the URL

$('form').submit(function(event){
event.preventDefault();
var userData = "https://maps.googleapis.com/maps/api/geocode/json?address="+$('input#city').val()+"&key=MY_API_KEY";
console.log(userData);
$.ajax({
type: "GET",
url : userData,
success: function(data){
$.each(data['results'][0]['address_components'], function(key, value) {
if(value["types"][0] == "postal_code"){
$('.alert-success').fadeIn(2000).html('Post/ZIP Code: '+value["long_name"]);
}
});
}
})
});
So, I have this code, above, which is currently returning no error nor any results as desired.
It works fine as long as I put the entire 'https://maps.googleapis.com/maps/api/geocode/json?address=""&key=""' string in the url: "", section of the ajax, but when trying to pass my variable in it doesn't want to do anything.
From what I've found variables should pass through easily enough into the ajax call so I'm kind of lost.
Your condition if (value["types"][0] == "postal_code") { is not working.
Check the returned data object via console.log.
Here is a working fiddle without it:
https://jsfiddle.net/1t82y0xa/
You need to URL encode the string returned by $('input#city').val()
related question: JavaScript URL encode
Note: Not all geocoder records return members of the response array with a postal_code type (like for example a query for "New York, NY", it has multiple zip codes).
var userData = "https://maps.googleapis.com/maps/api/geocode/json?address="
+ encodeURIComponent($('input#city').val())
+ "&key=MY_API_KEY";
console.log(userData);
$.ajax({
type: "GET",
url: userData,
success: function(data) {
console.log(data);
$.each(data['results'][0]['address_components'], function(key, value) {
if (value["types"][0] == "postal_code") {
$('.alert-success').fadeIn(2000).html('Post/ZIP Code: ' + value["long_name"]);
}
});
}
});

How can I parse JSON using the data parameter in JQuery?

I am making a web application using Jersey and JQuery for client-side.
I have the following URL that returns a JSON string:
http://localhost:8080/messenger/webapi/messages/1
returns:
{"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"}
when typed into the browser.
Now I am attempting to get this data client-side using the following JQuery functions:
var rootURL = "http://localhost:8080/messenger/webapi/messages";
$(function() {
$('#btnRegister').click(function() {
var username = $('#username').val();
addMessage();
});
function addMessage() {
var url = rootURL;
$.ajax({
type: 'GET',
url: rootURL +"/1",
dataType: "json", // data type of response
success: (function(data) {
var obj = jQuery.parseJSON(data);
alert('ID: ' + obj.id);
})
});
}
});
EDIT: When the "btnRegister" is pressed nothing is displayed at all
which just doesn't make sense to me.
There is some unwanted $ wrapping in success callback function, also there is no need to parse the response as you set dataType:'json'. For better understanding of $.ajax() read documentation here.
$(function() {
$('#btnRegister').click(function() {
var username = $('#username').val();
addMessage();
});
function addMessage() {
var url = rootURL;
$.ajax({
type: 'GET',
url: rootURL + "/1",
dataType: "json", // data type of response
success: function(data) {
//----^----------- remove the $ sign
alert('ID: ' + data);
}
});
}
});
You can access the value using obj.prop or obj['prop']
var obj= {"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"};
alert(obj.author);
alert(obj['author']);

Pass Json Object and String Value at once in Ajax

I want to pass a Json Object and String Value together in ajax call. I have attached my code below.
$('#ddcountryid').change(function () {
var jdata = ko.mapping.toJSON(viewModel);
var Cid = $(this).val();
//alert(intCountry);
$.ajax({
url: '#Url.Action("PopulateDropDown", "Pepmytrip")',
type: 'POST',
data: jdata,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.redirect) {
location.href = resolveUrl(data.url);
}
else {
ko.mapping.fromJS(data, viewModel);
}
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
},
});
});
My Action Method
public JsonResult PopulateDropDown(Wrapper wrapper, string cID)
{
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
I am getting wrapper object with Values, but how can get the CID as well. Can anyone please help me on this??.
you can pass it as query string parameter:
var Cid = $(this).val();
$.ajax({
url: '#Url.Action("PopulateDropDown", "Pepmytrip")' + '?cID=' + Cid,
...
server side:
public JsonResult PopulateDropDown(Wrapper wrapper, string cID)
{
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
OR add a new property to your Wrapper object as Gavin Fang suggested:
var Cid = $(this).val();
viewModel.Cid = Cid;
var jdata = ko.mapping.toJSON(viewModel);
server side code:
public JsonResult PopulateDropDown(Wrapper wrapper)
{
var cid = wrapper.Cid;
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
I think you can add a property to store you 'CID' to your viewModel.
and you can get the CID in the 'success' function in javascript in here, I think.
You can achieve this is two ways:
You can add extra field for existing json 'jdata' by defining field jdata.cid = null; and assigning it as jdata.cid = $(this).val();.
Prepare an object to hold both json data and string value:
var obj = {"json": jdata, "string":$(this).value()};
then pass obj in data parameter

JSONP adapter Phonegap project not working

I am using the sample code (slightly modified) to implement a JSONP adapter found here: http://coenraets.org/blog/2013/04/building-pluggable-and-mock-data-adapters-for-web-and-phonegap-applications/
My modified in-memory adapter works, but when I try to change from using the mock data, to a JSONP data object from a remote server, it doesn't work. Below is my memory adapter:
var JSONPAdapter = function() {
this.initialize = function(data) {
var deferred = $.Deferred();
url = data;
deferred.resolve();
return deferred.promise();
}
this.findById = function(id) {
return $.ajax({url: url + "/" + id, dataType: "jsonp"});
}
this.findByName = function(searchKey) {
return $.ajax(
{
url: url + "?Name=" + searchKey,
dataType: "jsonp",
success: function (data) { },
error: function (XHR, textStatus, errorThrown) { alert("error: " + errorThrown + '\nurl: ' + url + "?Name=" + searchKey);
}
});
}
this.getAll = function getAll() {
return $.ajax({ url: url, dataType: "jsonp" });
}
var url;
}
You don't need the /callback=? appended to the end of the url. This is taken care of automatically because the dataType is set to 'jsonp'.
I suspect this is due to the scope of your JSONData variable.
It is not initialised correctly if there is an error within the getJSONData() call. Try declaring the JSONData variable before the function is defined.

Categories

Resources