Question, why and how do i get my json api data to display. to display my api infomation
I am new to api and am trying
json data
[{"title":"One article - API 1 - 2017-04-25 15:43:20"},{"title":"Another article - API 1 - 2017-04-25 15:43:20"},{"title":"Great article - API 1 - 2017-04-25 15:43:20"}]
I have a small js file that im using to get my api
$(document).ready(function () {
$('#get-data').click(function () {
var showData = $('#show-data');
$.getJSON('https://some api ', function (data) {
console.log(data);
var items = data.title (function (item) {
return title;
});
showData.empty();
if (items.length) {
var content = '<li>' + items.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
}
});
showData.text('Loading the JSON file.');
});
});
I then have a html part to display the api info onlick
<body>
Get JSON data
<div id="show-data"></div>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="example.js"></script>
</body>
You need to iterate over the items in data to build your HTML and then append it to the showData div.
I also changed how you are building your <li> a little bit for security purposes. If you set the HTML of the <li> equal to each item's title property coming back from data, and the title contains malicious HTML/scripts, your application has been successfully compromised with an XSS attack.
As a general rule of thumb, never set HTML unless you absolutely have to - especially if it is coming from a third-party source.
$(document).ready(function() {
$('#get-data').click(function() {
var showData = $('#show-data');
$.getJSON('https://some api ', function(data) {
showData.empty();
var items = data.map(function(elem) {
return $("<li />", {
text: elem.title
});
});
var list = $('<ul />').append(items);
showData.append(list);
});
});
});
Get JSON data
<div id="show-data"></div>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="example.js"></script>
There is no method data.title() you want Array#map()
Scaled down version:
$.getJSON('https://some api ', function(data) {
// map title properties into flattened array
var items = data.map(function(item) {
return item.title;
});
if (items.length) {
var content = '<li>' + items.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
}
});
DEMO
The data returned in $.getJSON is a collection of objects. That might have been clear to you while you consoled the response.
Now, loop through data and you can access each object and insert title into li.
See a sample code below:
data.map(function(obj) {
console.log(obj.title) // use this in your <li>
})
Related
I'm have trouble accessing json data within the console. If for instance I wanted to type in courses[0].name or courses.length, I get the error "courses is not defined". I'm definitely missing something here but I'm unsure how to go about it. The list is generating just fine on the DOM, but I want want to access specific parts within the array.
$(document).ready(function () {
var showData = $('#show-data');
$.getJSON('../undergraduate/ug.json', function (data) {
console.log(data);
var courses = data.courses.map(function (course) {
return course.code + ': ' + course.name;
});
if (courses.length) {
var content = '<li>' + courses.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
}
});
});
<body>
Get JSON data
<div id="show-data"></div>
</body>
The json data also seems to be appearing fine initially on load within the console log:
Any help would be very appreciated. Thanks in advance!
this is my first time here so i hope i don't break any rules.
I have a Jquery code that retrieves info from an API that is written from a .net controller. Retrieving the infomration from the API works well, but now that i have to make the user sign in to view the API(Json), it of course stopped working in jquery. Is there anyway i can let the Jquery code "sign in" so it can retrieve data from that API while it's protected with password (authorize)?
Thanks
UPDATE
here is the Jquery Code
$(document).ready(function () {
var showData = $('#show-data');
$.getJSON('url/here', function (data) {
console.log(data);
var items = data.map(function (item) {
return item.id + ': ' + item.firstName + ': ' + item.lastName;
});
showData.empty();
var content = '<li>' + items.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
});
});
The code below is commented throughout. It is my understanding that I'm retrieving the JSON data and passing it to the 'results' div in my HTML view. This actually returns nothing, and it's difficult to debug because I can't output anything to the console.
// Here is how the final url should look:
// api.openweathermap.org/data/2.5/weather?q=Chicago&APPID=2e76bb25aa22d34ca062d764f4f3114b
var weatherSearch = '';
// weather-search is my html form id. On submit, send the input
// (which is city name) to the function getWeather.
$('#weather-search').submit(function(event) {
weatherSearch = $('#weatherQuery').val();
event.preventDefault();
getWeather(weatherSearch);
});
// getWeather has params q (city name), and APPID (API key).
function getWeather(weatherSearch) {
var params = {
q: weatherSearch,
APPID: '2e76bb25aa22d34ca062d764f4f3114b'
};
// This is the url that goes before the params.
url = 'http://api.openweathermap.org/data/2.5/weather/';
// Request data using url and params above.
// Does $.getJSON format the url properly?
$.getJSON(url, params, function(data) {
// Pass JSON data to showWeather function.
showWeather(data.items);
});
}
function showWeather(weather) {
// Show JSON data (weather) in html div id="weatherResults"
$('#weatherResults').html(weather);
}
Here is the associated HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>weather</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="openweather.js"></script>
</head>
<body>
<form id="weather-search">
<input type="text" value="" id="weatherQuery" />
<input type="submit" />
</form>
<div id="weatherResults">
</div>
</body>
</html>
Here's a codepen for the program
This answer demonstrates multiple ways to request and view data.
The code snippet below queries the web service using either jQuery or plain javascript. The returned data is displayed on the screen using JSON.stringify() and Google Prettify. The data is also sent to the console. Interestingly, the OpenWeatherMap service makes a good guess when the city name is misspelled.
The problem with OP's code appears to be this line: showWeather(data.items); which tries to display an object as html.
Run the snippet to try
var url = 'http://api.openweathermap.org/data/2.5/weather?APPID=2e76bb25aa22d34ca062d764f4f3114b';
// plain javascript version
function getWeather(city) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url + '&q=' + city, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
showData( data );
}
}
xhr.send();
}
// jQuery version
function getWeather2( city ) {
$.getJSON(url + '&q=' + city, showData );
}
// display json weather data
function showData( data ) {
window.city.value = data.name;
window.stdout.innerHTML = JSON.stringify(data, false, ' ');
window.stdout.className = 'prettyprint';
PR.prettyPrint();
if (window.console) window.console.log( data );
}
// sample data
getWeather('Berlin');
input {border: 1px solid black;}
button {width: 8em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/run_prettify.js?autoload=false&skin=sunburst&lang=js"></script>
Enter City: <input id="city" >
<button onclick="getWeather(window.city.value)">Use JS</button>
<button onclick="getWeather2(window.city.value)">Use jQuery</button>
<pre id="stdout" class="prettyprint"></pre>
You can use console.log or the dom to print messages for debugging. You can run a callback like this to find out if a request fails, this will tell you more infomation:
$.getJSON(url, params, function(data) {
// Pass JSON data to showWeather function.
showWeather(data.items);
}).fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
Using the complete URL (http://api.openweathermap.org/data/2.5/weather/?q=Chicago&APPID=2e76bb25aa22d34ca062d764f4f3114b) directly in a browser returns some JSON with data about chicago -- but that JSON does NOT contain an item property. Thus, your data.items is null and nothing is shown.
Just check what you actually get from the browser and adopt your code accordingly (e.g. data.name would give you "Chicago", or simply use showWeather(data); to show all JSON you got).
I did a cross-domain JSON request with YQL and it returns me the JSON code in a table <div> in the html file.
Now my problem is that I don't know to get this data and put it in a table.
This is the code (in JS file):
// JavaScript Document
$(document).ready(function(){
var container = $('#target');
$('.ajaxtrigger').click(function(){
doAjax($(this).attr('href'));
return false;
});
function doAjax(url){
// if it is an external URI
if(url.match('^http')){
// call YQL
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=xml'&callback=?",
// this function gets the data from the successful
// JSON-P call
function(data){
// if there is data, filter it and render it out
if(data.results[0]){
var data = filterData(data.results[0]);
container.html(data);
// otherwise tell the world that something went wrong
} else {
var errormsg = "<p>Error: can't load the page.</p>";
container.html(errormsg);
}
}
);
// if it is not an external URI, use Ajax load()
} else {
$('#target').load(url);
}
}
// filter out some nasties
function filterData(data){
data = data.replace(/<?\/body[^>]*>/g,'');
data = data.replace(/[\r|\n]+/g,'');
data = data.replace(/<--[\S\s]*?-->/g,'');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,'');
data = data.replace(/<script.*\/>/,'');
return data;
}
});
and here is the html code:
<body>
<div id="doc" class="yui-t7">
<div id="hd" role="banner">
<h1>
Ajax with jQuery - using YQL
</h1>
</div>
<div id="bd" role="main">
<h2>
Demo
</h2>
<ul>
<li>
<a class="ajaxtrigger" href="ajaxcontent.html">
Load Ajax Content
</a>
</li>
<li>
<a class="ajaxtrigger" href="linkpage">
Get cspro.json
</a>
</li>
</ul>
<div id="target">
<!-- <script>window.alert(container)</script> -->
</div>
<h2>
Formatted List
</h2>
</div>
<div id="placeholder"></div>
<!-- <script> document.getElementById("placeholder").innerHTML = container.html(data);
</script> -->
<h2>
TEST
</h2>
</div>
<script src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script src="code.js"></script>
<script src="using-yql3.js"></script>
</body>
I've try with:
// $.getJSON(data, function(json){
// figure out the format of the answer here...
//
document.getElementById("placeholder").innerHTML=prova.buy.currency+" "+prova.sell.currency+" "+prova.offer[0].amount+" "+prova.offer[0].rate+" "+prova.offer[0].seller.name;
but it didn't work.
(UPDATE) after your indications, I've tested this:
// TEST
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=json'&callback=?", // QUESTO รจ URL cui segue la "," e poi function(data)
// this function gets the data from the successful
// JSON-P call
function(data){
document.getElementById('placeholder').value = JSON.stringify(data,null,' '); //MIO
// if there is data, filter it and render it out
if(data.results[0]){
var data = filterData(data.results[0]);
container.html(data);
alert(data); //MIO TEST
// otherwise tell the world that something went wrong
} else {
var errormsg = "<p>Error: can't load the page.</p>";
container.html(errormsg);
}
}
);
but it works up to alert(data) simply "jumping" the part of the code related to document.getElementById.
I've also changed the "xml" request into "json" request...
SECOND UPDATE
I've solved the problem with the "div id=placeholder" in the html table. Seems it has some problems with this div, considering that changing the "div id" with a "texture id=placeholder" it works.
So, now I have the whole json string in my text area.
I've tried the getJson command to recover a parte of the data and get it in a table, but again I've having some problems.
I can't understand with the code you suggested to me, I have a json code, why I can't extract it and show the part i need?
FINAL PARTIAL UPDATE
The problem was that the "data" filter wasn't eliminating "" tag from data, so that the parse.Json(data) was unable to read the format!
Right know I retrieve the information I need.
Here's the final .js code:
// JavaScript Document
$(document).ready(function(){
var container = $('#target');
$('.ajaxtrigger').click(function(){
doAjax($(this).attr('href'));
return false;
});
function doAjax(url){
// if it is an external URI
if(url.match('^http')){
// call YQL
// TEST
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=json'&callback=?",
// this function gets the data from the successful
// JSON-P call
function(data){
// if there is data, filter it and render it out
if(data.results[0]){
**var data = filterData(data.results[0]);**
container.html(data);
alert(data); // TEST VERIFY (after FILTER before data extraction)
document.getElementById("prova1").value = data; // TEST full data return in a textarea
var obj = $.parseJSON(data); // JSON elements retrieve
alert(obj.sell.currency); // TEST for element retrieve
// TEST END
// otherwise tell the world that something went wrong
} else {
var errormsg = "<p>Error: can't load the page.</p>";
container.html(errormsg);
}
}
);
// if it is not an external URI, use Ajax load()
} else {
$('#target').load(url);
}
}
// filter out some nasties
function filterData(data){
**data = data.replace(/<body>/,'');** // INTERTED THIS ONE TO REMOVE body tag
data = data.replace(/<?\/body[^>]*>/g,'');
data = data.replace(/[\r|\n]+/g,'');
data = data.replace(/<--[\S\s]*?-->/g,'');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,'');
data = data.replace(/<script.*\/>/,'');
return data;
}
});
Your main problem is that you are requesting data in XML format. Suggest changing your query string to format=json. That will return a javascript object that you can work with more easily.
Since you are already using jQuery I highly recommend the DataTables plug-in.
Here's a code snippet that illustrates the data formats returned from Yahoo. And the Yahoo Console is also very helpful when testing.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<button onclick="json()">GET JSON</button><button onclick="xml()">GET XML</button>
<textarea id="stdout" style="width:100%;height:40em;"></textarea>
<script type="text/javascript">
function json() {
var url = 'https://query.yahooapis.com/v1/public/yql?q=show%20tables&format=json&diagnostics=true&callback=?';
$.getJSON( url, function(data) {
document.getElementById('stdout').value = JSON.stringify(data,null,' ');
});
}
function xml() {
var url = 'https://query.yahooapis.com/v1/public/yql?q=show%20tables&format=xml&diagnostics=true&callback=?';
$.getJSON( url, function(data) {
document.getElementById('stdout').value = JSON.stringify(data,null,' ');
});
}
</script>
</body>
</html>
You may want to look at this library: https://github.com/IonicaBizau/jQuery-cross-domain-requests
I am using a javascript Get call to grab the json data for a collection I created in deployd. I got this code directly from the deployd backend. It gives me a json array that is put into the console, but I am far from figuring out how to parse the json not sure if thats the right term, and output it into seperate p tags for each item within in the collection.
I also have included jQuery and I am assuming based on what I have looked into online that it makes it much easier to do so. Also if there is a better library than jQuery to learn to do this with, or something that makes more sense for deployd lets say Angular, I would love to be steered in the right direction.
Here is the javascript get request provided.
dpd.things.get(function (result, err) {
if(err) return console.log(err);
console.log(result);
});
I have tried looking at a example app off the deployd site to see how they did it but havent quite figured it out here is my failed attempt below
<body>
<h1>Welcome to Deployd!</h1>
<p>You've just created a Deployd app. You can add front-end files in the <code>public</code> folder.</p>
<p>If you're new to Deployd, have a look at the Getting Started Guide or <a href="http://docs.deployd.com/docs/getting-started/your-first-api.md">Hello World Tutorial<a>.</p>
<p class="hide" id="empty">You don't have any todos! Add one now:</p>
<ul id="todos" class="unstyled"></ul>
</body>
<script>
function getTodos() {
// Get all todos
dpd.things.get(function(result, err) {
if (err) {
// Alert if there's an error
return alert(err.message || "an error occurred");
}
if (!result.length) {
$('#empty').show();
}
// todos is an array
result.forEach(function(thingy) {
renderTodo(thingy);
});
});
}
function renderTodo(thingy) {
var $el = $('<li>');
// $label = $('<label class="checkbox">')});
$el.appendTo('#todos');
$('#empty').hide();
}
</script>
NEW RECCOMENDED CODE NOT WORKING
function getTodos() {
// Get all todos
dpd.things.get(function(result, err) {
if (err) {
// Alert if there's an error
return alert(err.message || "an error occurred");
}
if (!result.length) {
$('#empty').show();
}
// todos is an array
result.forEach(function(thingy) {
renderTodo(thingy);
});
});
}
function renderTodo(thingy) {
var $el = $('<li>');
$el.text(thingy);
$el.appendTo('#todos');
$('#empty').hide();
}
Here is the site running on localtunnel so you can see the console. https://twig.localtunnel.me
Try adding 'thingy' in the code so it will display the items returned from the collection; Just make sure a collection is being returned.
If thingy is plain text:
var $el = $('<li>')
$el.text(thingy);
If thingy includes html with text:
var $el = $('<li>')
$el.html(thingy);
I ended up doing this in the end based off of this stack overflow answer
dpd.things.get(function(result, error) {
console.log(result);
$.each(result, function(i,result){
content = '<p id=" ' + result.name + ' ">'
+ result.name + '</p>' + '<p>' + result.about +
'</p>' + '<p>' + result.id + '</p>'
$(content).appendTo("#test");
});
});