I want to call the Google API from JavaScript code.
I have a URL to search nearby locations like this:
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=ww.www,yy.yyy&radius=50&key=XXXXX
When I run that through browser I get the correct JSON result.
But I want to get the JSON response from my JavaScript code.
I don't want to show these locations in Google Maps, just to get the JSON object and manipulate it according to my needs.
I tried to send it via an Ajax call, but it gives an error.
This is what I am using:
//remember to add your API KEY to the url below.
$.ajax({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address=UK&key=<KEY-GOES-HERE>',
type: 'GET',
success: function(res) {
alert(res.status); //responds with "OK"
}
});
You will need to use the jQuery tag for it to function, as its using the jQuery ajax function:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
Use the places-library of the Maps-Javascript-API: https://developers.google.com/maps/documentation/javascript/places#place_search_requests
You may use the nearbySearch of this library also without a map(but when you print data without a map you must include the Logo)
The URL you've posted may not be requested via AJAX, because the server doesn't send the appropriate headers for a XDomainRequest
Related
I Am new in working with json and jquery. I am trying to study the basics of json and jquery by working on some example. So I use existing json data in http://api.androidhive.info/contacts for my example. I want to display this data in my HTML page. My code is:
<html>
<head>
<title>jQuery Ajax Example with JSON Response</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$(':submit').on('click', function() { // This event fires when a button is clicked
alert("submitt worked.");
$.ajax({ // ajax call starts
url: 'http://api.androidhive.info/contacts/', // JQuery loads serverside.php
type: "GET",
dataType: 'json', // Choosing a JSON datatype
success: function (msg) {
alert("ajax worked.");
JsonpCallback(msg);
},
})
function JsonpCallback(json)
{
for (var i in json.contacts) {
$('#wines').append('contacts: ' + json.contacts[i] + '<br/>');
}
}
return false; // keeps the page from not refreshing
});
});
</script>
</head>
<body>
<form method="post" action="">
<button value="all" type="submit">Get!</button>
</form>
<div id="wines">
<!-- Javascript will print data in here when we have finished the page -->
</div>
</body>
</html>
can any one please give me some brief introduction to JSON and how it's working ?
Thanks in advance.
You are iterating the JSON wrong, in your case since you are using jQuery (as mentioned) you can use the $.each(json, callback); helper fron jQuery, you can see the documentation here Jquery $.each documentation
For an example implementation I've created this JSFIDDLE LINK
for you. Have a great day ahead. Don't forget that JSON means
Javascript Object Notation
It's an object.
$.each(jsonData.contacts, function(k, v)
{
console.log(v.name);
$('#name').append('<li>'+v.name+'</li>');
});
jQuery
Am try to study the basics of json and jquery
Is a Javascript library with lots of very usefull methods. If you want to create a dynamic website it is very recommended to look into jQuery. There are many site with great explanation on what jQuery can do. As far as your example is concerned: There is an issue when passing variables/data from one framework to another or even when simply storing data. Here comes JSON.
JSON
Or JavaScript Object Notation (JSON) is used to solve exactly that problem. What is basically does is take all the desired data (array, variable, object, string etc.) and writes it in a human readable and for other frameworks readable fashion. I use JSON to store data in files when no database is available or when passing data from one framework to another (like JS <-> PHP).
Your example code
What happens here:
$(':submit').on('click', function() { // This event fires when a button is clicked
alert("submitt worked."); // not yet
$.ajax({ // ajax call starts
url: 'http://api.androidhive.info/contacts/', // JQuery loads serverside.php --> this I don't know
type: "GET", // communication type
dataType: 'json', // Choosing a JSON datatype
success: function (msg) { // here, the whole content of the url is read, idealy it is in JSON format ofc
alert("ajax worked."); // hoorray
JsonpCallback(msg);
},
})
There is the serverside.php file that receives a GET command and returns HTML. All the HTML content is in JSON type (so no <stuff>, i.e. no actual HTML) and your success function returns that content in the msg variable. Typically you use something like
var obj = JSON.parse(text);
to convert the JSON data to Javascript variables. Read this here JSON in Javascript
JSONP
Now what if you want to do some domain crossing (as you suggested), then I strongly recommend to read this here What is JSONP all about? . It explains what JSONP is all about
I'm trying to use the API from https://developer.forecast.io and I'm getting a JSON response, this is the first time I'm using an API and all I really need to know is, how do I assign the JSON response I get back from their API to elements on my page. Thanks!
This is done with a script-tag in my header:
script(src='https://api.forecast.io/forecast/APIKEY/LAT,LON')
http://api.jquery.com/jQuery.ajax/ you need to add a success callback, at the bottom of that page are examples you can look at.
EDIT
ok i saw that you are using a script tag with the request, since the api is outside your current domain you need to make a JSONP request
$(document).ready(function(){
$.ajax({
url: 'https://api.forecast.io/forecast/APIKEY/LAT,LON',
dataType: 'jsonp',
success: function(data){
//do whatever you want with the data here
$("body").append(JSON.stringify(data));
}
});
});
off course you need to make some tweaks to that piece of block but you get the idea
What you're looking for is DOM manipulation. DOM is the HTML Document Object Model, an object representation of the HTML comprising a document. There are a lot of ways to go about this, but one of the more popular Javascript libraries for performing this task is jQuery. See their help documentation category on manipulation for more information.
OK, based on your clarification, you're not yet using AJAX. I say "not yet", because you're going to need to. Again, I'll recommend jQuery for that, and their own documentation as the best resource. For a simple "get", your easiest option is the getJSON method.
So, at a very simple level you might do something like:
$(function(){
$.getJSON('url_to_api', function(data) {
$("#SummaryBox").append("<div>" + data.hourly.summary + "</div>");
}
});
what I need to do is read the content of a "public" google spreadsheet (by public I mean that I saved the sheet clicking on "File > Publish to the web", so it's accessible without the need to be logged in into a google account), and, why not, write something into it too.
googlin' around, I found that I can access the sheet and get the xml equivalent of the sheet content with something like
https://spreadsheets.google.com/feeds/list/<sheetCode>/od6/public/values
It works great if I load that url into a browser. But I need to find a "javascript-way" to get and handle the returned value, ie the xml (or json, but xml would be preferable).
I tried to use an ajax call, but I think there's something messy with the protocol.. I can't get the server response correctly.
$.ajax({
type: "GET",
url: "https://spreadsheets.google.com/feeds/list/<sheetCode>/od6/public/values",
success: function(data){alert("yeah");},
error: function(){alert("fail..");},
dataType:"xml",
});
I also tried to get the json instead of xml, adding "?alt=json" to the url and changing the datatype, but I still have the problem..
Any idea / suggestion?
Thanks in advance, best regards
You need to request with a JSONP call and you need to specifiy a callback - method. This can be done in jQuery using:
var url = 'https://spreadsheets.google.com/feeds/list/<CODE>/od6/public/values?alt=json-in-script&callback=?';
jQuery.getJSON(url).success(function(data) {
console.log(data);
}).error(function(message) {
console.error('error' + message);
}).complete(function() {
console.log('completed!');
});
Documentation and samples for google spreedsheets .
I am trying to make a simple ajax request(cross-domain) using Json.
Here's my code :
$("#unsub").live('click', function() {
$.ajax({
url: urly ,
type:'GET',
dataType:"json", //type JSON
success: function(data) { //do something
}
});
});
However, the response I am getting from the server is a html Div
<div id="handler"></div>
On button click I get an error on success "XML can't be the whole program".
Please note : i have to USE json to make the call no matter what and the call will always return a div. using jquery 1.3.2
Any help would be highly appreciated.
Thanks for the time.
Most of the time you need to provide the remote server a "callback" in url for the jsonp to be wrapped in. If API is not set up for JSONP, you need to use other methods to egt the JSOn with javascript. First check that API will deliver jsonp, and if so what params to put in the url
I have the following code I am using to send data to a MailChimp Newsletter List (API v3). Everytime I remove the type: POST from the function it attempts to post the data via GET and it sends the data properly (ok response in MailChimp API dashboard). When testing this in the browser (FF) I get a .part file with "true" response.
$(function(){
$("a#test").click(function(e){
e.preventDefault()
data = {
"apikey" : "667378947",
"id" : "90298590285",
"email_address" : "test#getmoxied.net",
"output" : "json"
}
$.ajax({
type: "POST",
url: 'http://us2.api.mailchimp.com/1.3/?method=listSubscribe',
data: data,
success: function(data){
alert(data);
},
error: function(){
alert("err");
}
})
});
});
Im pulling my hair out on this one, any insight is greatly appreciated.
Thanks in advance,
JN
There is an undocumented endpoint that uses JSONP to do cross-domain ajax requests.
Just change 'post?' to 'post-json?' and add '&c=?' to the end of the standard url to get the JSONP endpoint. This doesn't requires the API key to be exposed on the client-side, or the creation of a server-side view.
I wrote a jQuery plugin that uses this method, if that's useful at all
https://github.com/scdoshi/jquery-ajaxchimp
The main issue is what jc commented on your original post - this simply won't work due to Same Origin Policy issues. Firebug is not as vocal about why the GET call fails, but that's why it returns no data. If you watch that with the POST, you'll see Firefox doesn't even make the call. Chrome's js console on the other hand straight explains the Same Origin policy to you.
All in all, this is a very good thing if for no other reason than it prevents you from publicly publishing your account's API Key, which is a very bad thing to do. If the reason why doesn't immediately sink in, go read through the large number of methods available in the API and then realize that all you need to access them is that API Key.
The correct way to do this is to POST data back to your server, then make the request from there. There are several fully built PHP examples (one using jquery, even), here.
e.preventDefault();
data = {
"apikey" : "667378947",
"id" : "90298590285",
"email_address" : "test#getmoxied.net",
"output" : "json"
};
Could be? Semicolon is important. Hehe