Getting JSON data from a URL in Javascript - 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.
Related
How to Parse JSON from a web api in JavaScript
I am trying to parse this HummingBird api with sample url : http://hummingbird.me/api/v1/search/anime?query=naruto However, I do not know how to get each id seperately , or each name seperately. For e.g:- <!DOCTYPE html> <html> <body> <h2>Create Object from JSON String</h2> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = //make this display name </script> </body> </html> I want the demo element to display the title of the first one in the list. Can anyone tell me how I can possibly do this?
If you use jQuery below is the snippet you can use. var results = ""; $.get("http://hummingbird.me/api/v1/search/anime?query=naruto",function(data){ results = JSON.parse(data); }); console.log(results);
Download JQuery from here and put the file next to your html. Add this element between the html tag and the body <head> <script type="text/javascript" src="jquery-3.1.0.min.js"></script> </head> Replace document.getElementById("demo").innerHTML = with: $(document).ready(function(){ $.getJSON("http://hummingbird.me/api/v1/search/anime?query=naruto", null, function (data) {document.getElementById("demo").innerHTML = data[0].title}) }) JQuery is a JS library that makes life easy. The function below takes 1 function as an argument and executes it after the page has loaded $(document).ready() The next function makes an HTTP GET request and parses the response to js object $.getJSON("http://hummingbird.me/api/v1/search/anime?query=naruto", null,...) The next function gets the title of the first element of data function (data) {document.getElementById("demo").innerHTML = data[0].title}
mmm try this fiddle i don't know exactly how you read the file but if you get a string do the JSON.parse(STRING) before. https://jsfiddle.net/79a1abbL/3/
Get a javascript derived dom-tree element
My aim is to get an element <div id="calender"> and all what is in the element shown in a browser. The point is that normal get-html-source won't do the thing. The element what I am looking for does not exists in the html output of php-function file_get_contents. I have tried to get the source by php with xpath byt the help of http://us3.php.net/manual/en/class.domxpath.php which inludes a nice tool to get what is in any tag in the html page. But the problem here might be that the element (a calender) is formed to the loaded page by javascript and cannot be caught by server side php. So, is there a way I can catch such element (div) by javascript instead. There are script examples of javascript for this kind of problem (if I have understood them correctly) but currently I cannot get a simple javascript to work. An example below shows how I have tried to built up a code. $ajax thing here is just one path I have tried to solve the problem but don't know how to use it. More here I cannot figure out why the simple javascript functions do not work (just test purposes). <!doctype html> <html lang="fi"> <head> <meta charset="utf-8"> <title>load demo</title> <style> body { font-size: 12px; font-family: Arial; } </style> <script type="text/javascript"> function ok { alert "OK"; } function get_html (my_html){ alert "OK"; var l = document.getElementById('my_link').value; alert l; alert my_html; var url = my_html; $.ajax({ url: url, dataType: 'html' success: function(data){ //do something with data, which is the page 1.html var f = fs.open("testi_kalenteri.html", "w"); f.write(data); f.close(); alert "data saved"; } }); } </script> </head> <body> <p id ='my_link' onclick='get_html("lomarengas.fi/en/cottages/kuusamo-rukasaukko-9192")'>html-link</p> <p id ='ok' onclick='ok()'>show ok</p> </body> </html> Briefly, I have a link to a web page, which shows up a (booking) calendar in it but this calendar is missing in the "normal" source code, by file_get_contents (php). If I browse the html source with Chromes tools (F12) I can find the calendar there. T want that information get by javascript or by php or such.
If you read the source code of the page you point to (http://www.yllaksenonkalot.fi/booking/varaukset_akas.php), you notice that the calendar is loaded via an iframe. And that iframe points to that location : http://www.nettimokki.com/bookingCalendar.php?id_cottage=3629&utm_source=widget&utm_medium=widget&utm_campaign=widget Which is in fact the real source of the calendar... EDIT following your comment on this answer Considering the real link : http://www.lomarengas.fi/en/cottages/kuusamo-rukasaukko-9192 If the calendar is not part of the generated html, it is surely asynchronously generated (in javascript, client side). From this asumption, I inspected the source code (again). In the developper tools of my browser, in the Network section, where you can monitor what files are loaded, I looked for calls to server (everything but calls to resources : images, stylesheets...). I then noticed calls to several urls with json file extensions like http://www.lomarengas.fi/api-ib/search/availability_data.json?serviceNumber=9192¤tMonthFirstDate=&duration=7. I felt I was on the right track (asynchronous javscript calls to generate html with json datas), I looked for javascript code or files that was not the usual libraries files (jquery, bootstrap and such). I stumbled upon that file : http://www.lomarengas.fi/resources_responsive/js/destination.js. It contains the code that generates asynchronously the calendar. tl;dr The calendar is indeed generated asynchronously. You can't get the full html with a curl or file_get_content in PHP and you can't access it with ajax code (due to Same-origin policy). By the way, you should contact the site to see if you can access their api via PHP with their consent. Hope it helped you understand the whole thing...
To get <div id="calender"> you can use next code (jquery): <div id="calender"></div> <script> $("#calendar").click(function(){ alert('calendar was clicked'); }); </script> If I understand you correctly. I think you need appropriate php respond with some correct code inside php file: // json_handler.php <?php if (is_ajax()) { $return = $_POST; $return["ok"]="ok"; $return["json"] = json_encode($return); echo json_encode($return); } function is_ajax() { return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'; } and this is script wich is inside html: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> </head> <body> <a id="click">click</a> <script> $("document").ready(function(){ $("#click").click(function(){ var data = { "request": "request" }; data=$.param(data); // alert(data); $.ajax({ type: "POST", dataType: "json", url: "json_handler.php", data: data, success: function(data) { // here you will see echo respond from your php json_handler.php // also you can add here more javascript (jquery code) to change your page after respond alert(); } }); return false; }); }); </script> <body> <html> http://www.w3schools.com/jquery/jquery_ajax_intro.asp
Trouble combining jQuery and .php in Wordpress
I am trying to make a simple translation site here:http://traductordeinglesaespanol.co/. I created a simple php code that uses get to an external translation api which works fine. Here's the code: <?php if(!empty($_GET['text'])){ $trans_url ='http://api.mymemory.translated.net/get?q='.urlencode($_GET['text']).'&langpair=en|es' ; $trans_json = file_get_contents($trans_url); $trans_array = json_decode($trans_json, true); echo $trans_array['responseData']['translatedText']; } ?> Here is the simple html form: <form id="form" method="get" action="tran.php">Enter Text to be Translated below: <input name="text" type="text" id="test" /> <button id="but">Translate</button></form> <div class="results"></div> The translation works ok now but I what I would like to do is to grab the tran.php result using jQuery and show it in the "result" class below the form. I am trying to do this by the following: I loaded by editing the functions.php file so it loads jQuery and a .js script named tran.js. When I inspect element I see both jQuery and the script being loaded. In the script I put this basic code: jQuery(document).ready(function(){ $('#go').click(function() { $.ajax({ type: 'GET', url: 'tran.php', success: function(data) { $('.result').html(data); } }); }); }); and change action to to handle the form from this page. (tran.php is in the root directory.) But it isn't working at all. I suspect there is/are some crucial mistakes in the coding but being a complete beginer I cannot find where the mistakes are so any advice/correction would be greatly appreciated!
I somehow managed it to work! There was a small typo: data : 'text=' + to_be_translated; I replaced the ";" in the end with a comma and now I am getting the result like this: Let's say I input the text name to translate (nobre in spanish!), I get this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>estes</title> </head> nombre So I have to get rid of these headers somehow! Anyway I want to thank you again very much for your help! Gracias!
You should use ajax this way : var to_be_translated = "Hello"; $.ajax({ type: 'GET', url: 'tran.php', data : 'text=' + to_be_translated, success: function(data) { $('.result').html(data); } }); Here I added the "data" label, it says the JS variable to_be_translated will be seen as $_GET['text'] in PHP.
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.
How do I get data from this API link?
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