How do I get data from this API link? - javascript

I have just started looking into JavaScript and jQuery as of last night. I'm playing with the foursquare API (I already hate oauth but that might make for another post at another time) and it's hard when you have rudimentary knowledge, though I like this way of learning.
My question is really simple, I want to get data from an API URL that requires no authentication/authorisation. I then just want to display it (in my code I've made it display as an alert onclick).
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("button").click(function () {
$.getJSON('https://api.foursquare.com/v2/users/self/venuehistory?oauth_token=2ZO1PQOUAD5SXRAJOLZVH53RBQ1EB2C23FE2GUZLJYQUJ3SY&v=20121108',
function (data) {
alert(data);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP POST request to a page and get the result back</button>
</body>
</html>
When I click on the alert it feeds me "[object, Object]", obviously this is not what I am looking for. How do I get it to display the data from the URL?
I realise this is so incredibly basic (I know what to do, just not how to do it) so huge thanks to anyone who can help me.

You can't do alert() on a JSON object.
Instead, try this:
alert(JSON.stringify(data));
or, use console.log:
console.log(data);

to see each property and its associated value try
function(data){
for(att in data){
console.log(data[att]);
}

Just write
alert(data.tosource());
it seems this is what you are looking for

Related

Call blockchain.info API with javascript or jQuery

Is it possible to call the blockchain.info API with javascript or jQuery?
I'm trying to get all the address info in json format with:
https://blockchain.info/address/1Nkmns4Pan2hknkQFfRCLnoKdR5VEP324J?format=json
Or:
https://blockchain.info/address/1Nkmns4Pan2hknkQFfRCLnoKdR5VEP324J?format=json&cors=true
From what i've read, it should be possible, but i'm starting to doubt it now. I know I can use a PHP script, a proxy, or some kind of YQL hack, but that won't really do what I want.
Basically, i've been trying various different versions of this:
<!DOCTYPE html>
<html>
<head>
<title>Blockchain.info API</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$.getJSON( "https://blockchain.info/address/1Nkmns4Pan2hknkQFfRCLnoKdR5VEP324J?format=json&cors=true", function( data ) {
$.each(txs.hash, function(key, value){
$('#test').append(key+': '+value+'<br>');
});
});
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
But so far, nothing's worked. Am I wasting my time here?
I don't recommend to get all details at once. That would be confusing because there's so much data on the JSON data. You can fetch every data from Blockchain's Query API's with AJAX.
For example, for getting a balance of a wallet, you can do:
$.ajax({url: "https://api.blockchain.com/q/addressbalance/bitcoinaddress", success: function(result){
$("#test").html(result);
}});
Hope this helps.

Getting JSON data from a URL in Javascript

I'm trying to read JSON data from a webserver but am lost. I don't get any errors but my code doesn't display anything either. Here's the sample
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON('http://api.example.com/madata.php?zip=08854&key=36e25aa7518a6092&callback=?', function(json) { //this works. but doesn't display any alerts or data
//$.getJSON('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo&callback=?', function(json) { //this works. notice the callback
//$.getJSON('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo', function(json) { //this also works
alert("good");
alert(JSON.stringify(json));
console.log(JSON.stringify(json));
});
});
</script>
</head>
<body>
<div id = 'placeholder'></div>
</body>
</html>
If you notice I've tried 3 $.getJSON statements with different URLs, 2 work, but the one with the key in the url doesn't display any alert upon success.
The "example" url "http://api.example.com/madata.php?zip=08854&key=36e25aa7518a6092&callback=?" works fine (when example replaced with an actual domain) if posted in the browser, and returns JSON data as
[{"FCCID":"52601","Calls":"WAWZ","StnFreq":"99.1","MktID":"18","StnOwner":"Pillar of Fire","StnNameHD1":"Star 99.1","StnDescrHD1":"Great Christian Music!","StnContentHD1":"Music","StnGenreHD1":"Religious","StnAltGenreHD1":null,"StnLangHD1":"English","StnWebsiteHD1":"www.star991fm.com","StnFBHD1":"facebook.com\/star991fm","StnTwitterHD1":"http:\/\/twitter.com\/star991fm","StnEmailHD1":"","StnSMSHD1":"","StnPhoneHD1":"(800) 791-0991","StnRebrHD1":"none","StnFeatHD1":"0","StnAEHD1":"Unknown","StnLogoHD1":"http:\/\/apistatic.ibiquity.com\/uploads\/logos\/5\/e\/5e0838767af7ede3d99de2c093be5c2b.png","StnAudioHD1":"","StnNameHD2":"WAWZ-HD2","StnDescrHD2":"Teaching and Preaching","StnContentHD2":"News\/Talk","StnGenreHD2":"Religious","StnAltGenreHD2":null,"StnLangHD2":"English","StnWebsiteHD2":"www.star991fm.com","StnFBHD2":"","StnTwitterHD2":"","StnEmailHD2":"","StnSMSHD2":"","StnPhoneHD2":"(800) 791-0991","StnRebrHD2":"none","StnFeatHD2":"0","StnAEHD2":"Unknown","StnLogoHD2":"http:\/\/apistatic.ibiquity.com\/uploads\/logos\/5\/e\/5e0838767af7ede3d99de2c093be5c2b.png","StnAudioHD2":"","StnNameHD3":"WAWZ-HD3","StnDescrHD3":"The Energy","StnContentHD3":"Music","StnGenreHD3":"Religious","StnAltGenreHD3":null,"StnLangHD3":"English","StnWebsiteHD3":"www.star991fm.com","StnFBHD3":"","StnTwitterHD3":"","StnEmailHD3":"","StnSMSHD3":"","StnPhoneHD3":"(800) 791-0991","StnRebrHD3":"none","StnFeatHD3":"0","StnAEHD3":"Unknown","StnLogoHD3":"http:\/\/apistatic.ibiquity.com\/uploads\/logos\/5\/e\/5e0838767af7ede3d99de2c093be5c2b.png","StnAudioHD3":"","StnNameHD4":"","StnDescrHD4":"","StnContentHD4":"","StnGenreHD4":null,"StnAltGenreHD4":null,"StnLangHD4":null,"StnWebsiteHD4":"","StnFBHD4":"","StnTwitterHD4":"","StnEmailHD4":"","StnSMSHD4":"","StnPhoneHD4":"","StnRebrHD4":"none","StnFeatHD4":"0","StnAEHD4":"Unknown","StnLogoHD4":"","StnAudioHD4":""},{"FCCID":"49587","Calls":"WDHA","StnFreq":"105.5","MktID":"20","StnOwner":"Greater Media","StnNameHD1":"","StnDescrHD1":"The Rock of New Jersey","StnContentHD1":"Music","StnGenreHD1":"Rock","StnAltGenreHD1":null,"StnLangHD1":null,"StnWebsiteHD1":"www.wdha.com","StnFBHD1":"www.facebook.com\/pages\/1055-WDHA","StnTwitterHD1":"http:\/\/twitter.com\/wdhafm","StnEmailHD1":"","StnSMSHD1":"","StnPhoneHD1":"(973) 455-1055","StnRebrHD1":"","StnFeatHD1":"0","StnAEHD1":"Live","StnLogoHD1":"http:\/\/apistatic.ibiquity.com\/uploads\/logos\/e\/b\/eb72e37fe8f446bd44d783b1b641fff0.png","StnAudioHD1":"","StnNameHD2":"","StnDescrHD2":"","StnContentHD2":"","StnGenreHD2":null,"StnAltGenreHD2":null,"StnLangHD2":null,"StnWebsiteHD2":"","StnFBHD2":"","StnTwitterHD2":"","StnEmailHD2":"","StnSMSHD2":"","StnPhoneHD2":"","StnRebrHD2":"","StnFeatHD2":"0","StnAEHD2":"Unknown","StnLogoHD2":"","StnAudioHD2":"","StnNameHD3":"","StnDescrHD3":"","StnContentHD3":"","StnGenreHD3":null,"StnAltGenreHD3":null,"StnLangHD3":null,"StnWebsiteHD3":"","StnFBHD3":"","StnTwitterHD3":"","StnEmailHD3":"","StnSMSHD3":"","StnPhoneHD3":"","StnRebrHD3":"","StnFeatHD3":"0","StnAEHD3":"Unknown","StnLogoHD3":"","StnAudioHD3":"","StnNameHD4":"","StnDescrHD4":"","StnContentHD4":"","StnGenreHD4":null,"StnAltGenreHD4":null,"StnLangHD4":null,"StnWebsiteHD4":"","StnFBHD4":"","StnTwitterHD4":"","StnEmailHD4":"","StnSMSHD4":"","StnPhoneHD4":"","StnRebrHD4":"","StnFeatHD4":"0","StnAEHD4":"Unknown","StnLogoHD4":"","StnAudioHD4":""}]
Please let me know if I'm doing something stupid here. I'm completely new to Javascript and just starting to learn.
$.get( "http://api.example.com/madata.php?zip=08854&key=36e25aa7518a6092&callback=?", function( data ) {
console.log(data.FCCID);
}, "json" );
This should help you. You can do what you want with the returned data.

Load external Web Page with jQuery

I was wondering what a good way to load an external web page (same server) would be. I have tried .load() and .get() however, The external page has a php script that spits out information every few seconds, the .load() and .get() only load it after the php is done. I have tried iFrame with does load it displaying the information being outputted by the PHP script. However, I don't really like to use iFrames. Thanks!
If your goal is for the PHP information (that is spit out every few seconds) to be updated on your site, then what you want to do is use AJAX, inside a setInterval routine.
See this post for the basics of AJAX -- it really is simpler than you might think. (You might first want to look at the simple examples linked at bottom).
Once you've got a simple ajax exchange happening, put that into a function called, for example, doAjax() -- and then create a setInterval, like this:
setInterval('doAjax();',60000);
Here is an important note when considering setInterval
Following is a simple copy/paste(able) example that will let you see exactly what I mean:
HTML/javascript: index.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style>
#timeDiv{width:40%;height:200px;background:wheat;padding:10px;}
</style>
<script type="text/javascript">
$(document).ready(function() {
doAjax();
window.setInterval(function(){
doAjax();
},2000);
}); //END document.ready
function doAjax() {
$.ajax({
type: "POST",
url: "your_php_processor.php",
success: function(myData) {
$('#thetime').html(myData);
}
});
}
</script>
</head>
<body>
<div id="timeDiv">
The time is: <span id="thetime"></span>
</div>
</body>
</html>
Now, the PHP side... your_php_processor.php
<?php
$d = date("h:i:s");
echo $d;

JQuery JSON data not displaying

I am having trouble displaying some jason from a page.
The data is there but I think it might have to do with this line:
document.write(fbResults.cats[0].title);
Here is the full html source:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.getJSON('http://mydomain.com/api/get_cats', function(fbResults) {
document.write(fbResults.cats[0].title);
});
});
</script>
</head>
<body>
</body>
</html>
And here is the data that it's reading:
{"cats":[
{"id":"1","title":"mytitle1","colour":"#EE297C"},
{"id":"2","title":"mytitle2","colour":"#EE412F"},
{"id":"3","title":"mytitle3","colour":"#F5821F"},
{"id":"4","title":"mytitle4","colour":"#00AEEF"},
{"id":"5","title":"mytitle5","colour":"#00B495"},
{"id":"6","title":"mytitle6","colour":"#006476"}
]}
It is not displaying anything on the page.
On firebug console I get this error:
The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must to be declared in the document or in the transfer protocol.
No traces of the json data there
What I'm I doing whong?
You shouldn't document.write after the page has loaded (which is certainly the case here).
If you want to write it to the page, you'll need to create HTML and append it. Just replace the document.write:
$('body').append('<p>'+fbResults.cats[0].title+'</p>');
Update:
Your example makes a fully qualified URL call. Is that server the exact same one that you're running the page from? If it isn't the XHR will just eat the request (and sometime not tell you). If you need to go cross domain, you'll need to use JSONp. If you're attempting to run this locally while pulling data from the net, it'll break.
Try this
$.each(fbResults.cats,function(index,item){
document.write(item.title);
});
Working sample : http://jsfiddle.net/zWhEE/8/
its seems work for me please check this
http://jsfiddle.net/TxTCs/1/

jquery ajax parse response text

Ok this is really frusturating me because I've done this a hundred times before, and this time it isn't working. So I know I'm doing something wrong, I just can't figure it out.
I am using the jQuery .get routine to load html from another file. I don't want to use .load() because it always replaces the children of the element I'm loading content into.
Here is my .get request:
$(document).ready(function() {
$.get('info.html', {}, function(html) {
// debug code
console.log($(html).find('ul').html());
// end debug code
});
});
The file 'info.html' is a standard xhtml file with a proper doctype, and the only thing in the body is a series of ul's that I need to access. For some reason, the find function is giving me a null value.
In firebug, the GET request is showing the proper RESPONSE text and when I run
console.log(html);
Instead of the current console.log line, I get the whole info.html as output, like I would expect.
Any ideas?
You cannot pull in an entire XHTML document. You can only handle tags that exist within the <body> of an html document. Frustrating. Strip everything from info.html that isn't within your <body> tag and try it again.
There are other potential ways around this issue - check below "Stackoverflow Related Items" at the base of this response.
From the Doc: (http://docs.jquery.com/Core/jQuery#htmlownerDocument)
"HTML string cannot contain elements that are invalid within a div, such as
html, head, body, or title elements."
Stackoverflow Related Items:
Simple jQuery ajax example not finding elements in returned HTML
What is the best practice for parsing remote content with jQuery?
I know this is an old post but I've been having the EXACT same frustrating problem for a couple of hours and have found a solution. For me what actually worked was to have the html content wrapped with a form tag.
So having the following html source:
<html>
<head>
<body>
<form>
<div id="content">Some Stuff</div>
</form>
</body>
</head>
</html>
With this jquery snippet should work:
var callback = function (data) {
alert($("#content", $(data)).html());
};
$.get(url, null, callback, null);
Hope this helps...
I have found this being pretty clean solution:
var elementInResponse = $("<div>").html(responseText).find(selector);
Wanting to do the same thing and knowing that JQuery load(..) does it, I had a look in the code. While you can't turn a complete html response directly into a JQuery object, you can append it to one so:
function(data, textStatus, xhr) {
$(target).html(jQuery("<div>").append(data).find("#snippet"));
// Create a dummy div to hold the results,
// inject the contents of the document into it,
// Locate the specified elements
}
The response from the server that goes into data is like:
<! doctype ... >
<html>
<head>
...
</head>
<body>
<div id="snippet">
<p>Some content here that we are interested in</p>
</div>
</body>
</html>
Try including whole body within a <div> tag, e.g. <body><div>content</div></body>.

Categories