using
http://maps.google.com/maps/api/geocode/json?address=xyz
we get a json file
I am wondering how can i maniupluate the results in javascript? How do i create the results object in javascript?
http://code.google.com/apis/maps/documentation/geocoding/index.html#JSONParsing
this doesnt really explain how they get the myJSONResult
You can use eval to parse the JSON into a JavaScript object, but this isn't recommended for security reasons. Use a JSON parser to turn the JSON string into a JavaScript object that you can manipulate.
Using eval:
myJSONResult = eval("{}");
Using the above linked parser:
myJSONResult = JSON.parse("{}");
The way you get the JSON is using an AJAX retrieval. This can be accomplished using hand coded JavaScript, but is far far easier using jQuery. Here's a quick example:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({ url: "http://maps.google.com/maps/api/geocode/json",
type: "GET",
dataType: "json",
data: { address: "1600+Amphitheatre+Parkway,+Mountain+View,+CA", sensor: "false" },
success: function(data, textStatus, XMLHttpRequest) {
console.log(textStatus);
alert(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus);
}});
});
</script>
BUT BUT BUT this will NOT work, because of the same origin policy. The way around that is to use a server side language of your choice (Perl, PHP, ColdFusion, ASP) to act as a proxy. That way the url value would be "yourproxy.php", "yourproxy.cfm", "yourproxy.asp" or whatever. That script would simply take the request it receives, act as a user agent to send the request to Google and retrieve the response (aka the URL that is the url value in the code above), and send out the results to your script.
The jQuery library handles the JSON processing for you, or you can use the information provided by Bob along with the hand rolled AJAX listed above. Note that hand rolled AJAX will need the same proxy solution to be able to get information from Google.
Also note that the Geocoding API you linked to is not meant for lots of dynamic queries. They lead you to the API V2 Client Geocoder, the API V3 Client Geocoder, and the Maps API for Flash Client Geocoder.
Related
My html page is making the following call:
<html>
<script src="https://someURL.com/api/getData?api_key=xyz&%26format=json">
</html>
It returns the following response:
data: abc123-abc456-efg678-ertyui789
How do I extract the
abc123-abc456-efg678-ertyui789
part into a var, so I can use it in other calls?
(I tried jquery, but it fails with CORS error, this is the only way I could get the response from the server)
var url ='https://someURL.com/api/getData?api_key=xyz&%26format=json',
jQuery.ajax({
type: 'GET',
url: url,
dataType: 'json',
success:function(res){
console.log("success");
console.log(res.data);
});
You can't.
The <script> element is designed to load a script and run it. A JSON document is not a script.
JSONP is a script, but if the service doesn't provide data in that format, then you can't use it.
Since an API key is involved, it is very likely that the service provides no mechanism for direct client-side access to the data because that would require that you give your secret key to all your visitors.
Fetch the data server-side instead.
Further reading
Aside, data: abc123-abc456-efg678-ertyui789 isn't a valid JSON document anyway so you might need a custom parser and not a JSON parser.
I'm using the jquery tabledit plug-in to update a database. Works perfectly like in the official examples.
I can succesfuly include a static dropdown with a fixed number of options (defined in custom_table_edit.js).
I'd like to be able to dynamically get those options from a database instead, but I don't know how to customize the code in custom_table_edit.js.
I can code this in php with a loop querying the database and generating a html <select> field. But I don't have knowledge of javascript or if it's even possible in this framework.
This is the custom_table_edit.js file. A dropdown is defined with three colour options. I want this dropdown to be dynamically produced.
// custom_table_edit.js
$('#example2').Tabledit({
url: 'example.php',
eventType: 'dblclick',
editButton: false,
columns: {
identifier: [0, 'id'],
editable: [[1, 'car'], [2, 'color', '{"1": "Red", "2": "Green", "3": "Blue"}']]
}
});
I really haven't tried anything because i'd like to know if it's possible to do in this framework.
Welcome to SO, nucelar.
What you are describing is a HTTP request from the client to server through JavaScript. This is commonly referred as AJAX or Asynchronous JavaScript And XML. This API enables you to manually send requests to the server and there are multiple implementations.
Because you are using jQuery I will recommend you to use the $.ajax function which is included in the jQuery library.
Down here I've made a very basic example of how to send a HTTP request to a server with the GET method to retrieve some data.
$.ajax({
url: 'https://yourdomain.com', // Where to send the request to. Can also be a file.
method: 'GET', // What method of request it uses.
success: function(data) { // When a response is succesfully received.
// Do something with the received data.
console.log(data); // Show what the data looks like in the console.
},
error: function(jqXHR, textStatus, errorThrown) { // When an error occurs while making a request.
console.log(jqXHR, textStatus, errorThrown); // Show the error in the console.
}
});
In your case the url property value might be the URL of a PHP file in which you query the database and return the result, as you mentioned you are able to do.
The response of the AJAX function (which is stored in the data variable in the success method) can be text, as in a string, or even JSON if you want to send structured data.
Beware of the Asynchronous part. This means that the AJAX code does not stop the execution of the rest of your JavaScript code, but simply continues and comes back whenever the HTTP request has been completed.
I hope that this is enough to get you started. Good luck and don't hesitate to ask questions.
I'm working on a Project for pedestrian navigation. For blind people, I'd like to tell them if there are any objects in the same street as they are, so they can orientate themselves.
I have a Json-file full with coordinates of trees from a city. I query geonames (with $.ajax) to get the nearby streets of the trees and want to store this information in a file. A json-file would be great, but I have no idea how to do this.
Can anyone tell me how I can create such a file? It has to be made only once.
Or do you know an alternative to store the data in a better way?
What I tried so far in js:
function writeToJson(streetNames){
$.ajax({
type: 'POST',
url: "scripts/treeStreets.php",
data: streetNames,
dataType: 'json',
error : function(parameters){
console.log("error");
console.log(parameters);
},
success: function(){
console.log("success");
}
});
}
And the php-script:
$streetNames = $_POST[streetNames];
file_put_contents('/live%20access/data/treeText.txt', $streetNames);
But this gives me an error.
You need to write a service in a language like PHP, Ruby, Python or Java. JavaScript has no ability to create a file on either the client or server so you'll need a service that the AJAX operation can call which will write the data to disk.
I'm trying to display the follow count of a twitter account, but when I hook into the API using this code:
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true", function(data) {
console.log(data);
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
I get a 200 ok report but with Data is null message.
But if I download the json file to my local machine and change the getJSON call accordingly, it works straight away.
Has anyone got any ideas on what could be causing this?
Thanks
Also just to add, if I put the Twitter API url into my browser it displays all the data, which makes it even weirder.
Maybe the problem lies with jsonP, since you are calling a remote server and you must specify you should use jsonP. Have you tried adding callback=? as a parameter
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true&callback=?", function(data) {
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
Taken from jQuery docs
JSONP
If the URL includes the string "callback=?" (or similar, as
defined by the server-side API), the request is treated as JSONP
instead. See the discussion of the jsonp data type in $.ajax() for
more details.
$.ajax({
url: 'https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true',
dataType: 'jsonp',
success: function(data){
console.log(data.followers_count);
}
});
Im trying out the new graph api for facebook. I'm trying to fetch some data using jquery ajax.
This is a sample of my javascript code, very basic...
var mUrl = 'https://graph.facebook.com/19292868552';
$.ajax({
url: mUrl,
dataType: 'json',
success: function(data, status) {
$('#test').html(data);
alert(data);
},
error: function(data, e1, e2) {
$('#hello').html(e1);
}
});
The url is to a page that does not need access tokens (try it using a browser), but the success function returns an empty object or null.
What am I doing wrong? Thankful for all help!
I have covered this and asked this question before. I made a quick tutorial which covers exactly this and explains it all.
In short:
JSON is not made for cross domain usage according to its same-origin policy. However the work around is to use JSONP which we can do in jQuery using the supported callback parameter in facebook's graph api. We can do so by adding the parameter onto your url like
https://graph.facebook.com/19292868552?callback=?
by using the callback=? jQuery automatically changes the ? to wrap the json in a function call which then allows jQuery to parse the data successfully.
Also try using $.getJSON method.
I was trying to do something similar, in testing I was able to get a working result which I saved on jsFiddle: http://jsfiddle.net/8R7J8/1/
Script:
var facebookGraphURL = 'https://graph.facebook.com/19292868552';
$.ajax({
url: facebookGraphURL,
dataType: 'json',
success: function(data, status) {
$( '#output' ).html('Username: ' + data.username);
},
error: function(data, e1, e2) {
$( '#output' ).html(e2);
}
})
HTML:
<html>
<body>
<div id="output">BorkBorkBork</div>
</body>
</html>
Hope that helps! :)
...The Graph API supports JSONP. Simply pass callback=methodname as an extra parameter and the returned content will be wrapped in a function call, allowing you to use a dynamically inserted script tag to grab that data.
http://forum.developers.facebook.com/viewtopic.php?pid=253084#p253084
You can't do cross-domain AJAX requests like that due to the same-origin policy. Instead, use Facebook's JavaScript SDK, which is based on a script tag.