Accessing JSON data from a url - javascript

I'm fairly new to web programming, so I'm sorry in advance if this is a dumb question. I've looked around and wasn't able to find anything very concrete on this so I figured I'd ask here.
I'm trying to make a script which reads a JSON file and returns some data. More specifically here's a link.
I want to search through and find where an world_id is equal to xxxx, and return the match_id. In another thread it one of the solutions was something similar to
var obj = JSON.parse(//JSON info here)
var a = obj.world_id
Can anyone point me in the right direction as to achieve this?

There are many reasons to add jQuery to a project. BUT. Please don't add jQuery just to get some json data. Javascript is perfectly capable of handling this one on its own, thank you:
// simple cross-browser ajax helper
var ajaxGet = function (url, callback) {
var callback = (typeof callback == 'function' ? callback : false), xhr = null;
try {
xhr = new XMLHttpRequest();
} catch (e) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
if (!xhr)
return null;
xhr.open("GET", url,true);
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && callback) {
callback(xhr.responseText)
}
}
xhr.send(null);
return xhr;
}
// example usage, grab the json data, loop it and log red_world_id to console
ajaxGet(
'https://api.guildwars2.com/v1/wvw/matches.json',
function (response) {
response = JSON.parse(response);
if (!response)
return;
var i, list = response.wvw_matches;
for (i in list) {
console.log(list[i].red_world_id); // outputs an id
}
});
Try it here: http://jsfiddle.net/7WrmL/
So basically, for your specific usage, instead of simply logging the ID to console, you can check each object's id properties against the desired matching id and, for example, return i for the index of the match (not sure I understand exactly what you're after there).
And keep in mind: use jQuery when you need it, not for everything and anything.
Documentation
XMLHttpRequest on MDN - https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
XMLHttpRequest ON MSDN (IE) - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx
JSON on MDN - https://developer.mozilla.org/en-US/docs/JSON
for... on MDN - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for

An easy way of getting the JSON data is by using jQuery, like this:
<div id="reply"></div>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$.getJSON(
"https://api.guildwars2.com/v1/wvw/matches.json",
function (data) {
$("#reply").html(JSON.stringify(data));
// or work with the data here, already in object format
});
});
</script>
See here: http://jsfiddle.net/mynetx/LwNKC/

Look at my code below. I used jquery to get content
var result;
$.get(
"https://api.guildwars2.com/v1/wvw/matches.json",
{},
function(data) {
var result = data;
}
);
var arr = JSON.parse(result);
var length = arr.length;
for (var i = 0; i < length; i++)
{
if(arr[i].red_world_id == 'xxx')
{
console.log('Got it');
}
if(arr[i].blue_world_id== 'xxx')
{
console.log('Got it');
}
if(arr[i].green_world_id== 'xxx')
{
console.log('Got it');
}
}
Look out for slip of the pen :).

Related

How to make an API call to show data?

I need to make an API call. The API consists of several arrays containing objects and the objects have 18 keys which I need to display.
How can I just display everything? I have tried doing fetch and ajax calls but none of them seem to work. What am I doing wrong here? Thanks beforehand.
async function events() {
return $.ajax("/api/address");
getEvents: function getEvents() {
return $.ajax("/api/address");
};
targetMarket: function targetMarket(id, events) {
return events.filter(function(event) {
return event.eventID === id;
});
};
eventsName: function eventsName(events, name) {
return events.filter(function(event) {
return events.event.eventID === events.eventID;
});
};
}
API calls can look a little intimidating starting off, keep at it!
Here's an example of getting simple data using an Ajax call to an API. This is in plain JavaScript, no libraries needed:
let cryptoData;
function ajaxGet(url) {
return new Promise(function(resolve, reject) {
let req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
if (req.status === 200) {
resolve(req.response);
cryptoData = JSON.parse(req.response); // the API response with the data is here (req.response). We use the JSON.parse() method to convert req.response string into a JSON object, since it originally comes in as a string.
showAjaxData();
} else {
reject(Error(req.statusText));
}
};
req.onerror = function(err) {
reject(Error("Looks like we've got an error..."));
};
req.send();
});
}
function showAjaxData() {
console.log(cryptoData[0]);
}
ajaxGet(`https://api.coinmarketcap.com/v1/ticker/bitcoin/`);
You can see the code in action at this JS Fiddle demo. Just remember to open the browser console to view the logged API data.
Feel free to check out this w3schools tutorial on Ajax calls.
Hope this helps :)

Check My Code. Is it a correct way to append?

function saveToDataBase(save_id,textarea_id,question_no,assg_name,testinput,testoutput)
{
document.getElementById(save_id).addEventListener('click',function(){
//alert("Hello");
var question=document.getElementById(textarea_id).value;
var question_id=assignment_name+question_no;
var request;
var url="saveQuesToDataBase.jsp?question="+question+"&question_id="+question_id+"&assg_name="+assg_name;
for(var i=0;i<testinput.length;i++)
{
var v=document.getElementById(testinput[i]).value;
url=url+"&testinput"+i+"="+v;
}
for(var i=0;i<testoutput.length;i++)
{
var v=document.getElementById(testoutput[i]).value;
url=url+"&testoutput"+i+"="+v;
}
var len=testinput.length;
url=url+"&size_of_arr="+len;
if(window.XMLHttpRequest)
{
request=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
request=new ActiveXObject("Microsoft.XMLHTTP");
}
try
{
request.onreadystatechange=function()
{
if(request.readyState==4 && request.status == 200)
{
alert(request.responseText);
}
};
request.open("GET",url,true);
request.send();
}
catch(e){alert("Unable to connect to server");
}
})
}
The function is called on click, but not redirected to saveQuesToDataBase.jsp . Please see if I could append things to url this way ? Tell me the better way.
testinput and testoutput are the two arrays of id's of textareas.
I used loop to retrieve id and to get the value.
For your code design,I have two suggestions:
a. First I would recommend you using jQuery ajax instead of original Ajax,it will hide the implement of different browsers.With it you can make it like below:
$.ajax({
url:your_request_url,
type:"post",//or get
data:your data,
success:function(data){},
error:function(){}
});
b. since Http Get method has parameter length limit,details can be found at maximum length of HTTP GET request?. You need to use POST instead of GET,while using POST,when can using data to pass more parameters to ajax:
var params ={};//define a parameter object
for(var i=0;i<testoutput.length;i++)
{
var v=document.getElementById(testoutput[i]).value;
params["testoutput"+i]=v;
}
$.ajax({
url:your_request_url,
type:"post",//or get
data:params,//passing the parameters.
success:function(data){},
error:function(){}
});

JavaScript static function in callback

Hi I've been trying to clarify this but there's something I'm still confused about. I know that you can't return values from asynchronous functions so I've referenced this answer's top answer Returning value from asynchronous JavaScript method?
What I'm trying to do is use the flickrAPI to get the biggest size image. The flickrAPI allows one to search images, so I use this to get the photo_id, then I use this photo_id to procses another request to the API's getSize method to get the URL for the biggest size photo.
The code looks a little messy as it is, because I have a method called flickrRequest which sends an XMLHttp request and gets back a JSON string. I know that I can achieve what I want by writing the functions as follows:
function flickRQforimage() {
...got ID
function flickrRQforSize() {
...got maxsizeURL
create image based on maxsizeURL here
}
}
but I was wondering if it was possible to do something like this
function flickRQforimage() {
...got ID
function flickrRQforSize() {
...got maxsizeURL
}
create image based on maxsizeURL here
}
or even create image based on maxsizeURL here
In general my question is whether it is possible to have a callback function that references another statically defined function (I think?). The specifics of the my function is that it takes a callback and the ID and URL processing happens in those callbacks:
flickrRQ(options, cb)
I am wondering whether/what would happen if that unnamed function is instead something else, say flickrRQ(options, processPhoto(data)), and then I define the function in a separate method. This just makes sense for me because I want to keep functionality for the URL processing separate in an attempt to make my code cleaner and more readable.
I tried the following below and it didn't work. Nothing prints. I even have a console.log in the processPhoto method. In fact anything inside of the flickrRQforSize method seems to not evaluate
flickrRQforSize(options, function(data) {
processPhoto(data)
}
even though in the flickrRQforSize definition, a callback function is taken as an argument. I'm suspecting there must be something about functions/async calls that I don't understand.
I hope this is clear -- if not, I can post my actual code.
Here's my code:
var flickrRequest = function(options, xhrRQ, cb) {
var url, xhr, item, first;
url = "https://api.flickr.com/services/rest/";
first = true;
for (item in options) {
if (options.hasOwnProperty(item)) {
url += (first ? "?" : "&") + item + "=" + options[item];
//parses to search equest;
first = false;
}
}
//XMLHttpRQ to flickr
if(xhrRQ == 1 ) {
xhr = new XMLHttpRequest();
xhr.onload = function() { cb(this.response); };
xhr.open('get', url, true);
xhr.send();
};
}
var processPhotoSize = function(photoJSON) {
var parsedJSON = JSON.parse(data);
var last = parsedJSON.sizes.size.length;
console.log(parsedJSON.sizes.size[last-1].source);
return parsedJSON.sizes.size[last-1].source;
}
...
flickrRequest(options, 1, function(data) {
...
flickrRequest(sizesOptions, 0, function(data) {
parsedJSON = JSON.parse(data);
console.log(parsedJSON);
processPhotoSize(data);
});
}

Get JSON data from external URL and display it in a div as plain text

I have an external resource similar to https://www.googleapis.com/freebase/v1/text/en/bob_dylan which returns a JSON. I want to display the value of result key in a div in html (lets say the name of the div is "summary"). Also the value of result key should be displayed in plain text.
The URL returns the json:
{ "result": "Bob Dylan, born Robert Allen Zimmerman, is an American
singer-songwriter, author, poet, and painter, who has been a major
figure in popular music for five decades. Much of Dylan's most
celebrated work dates from the 1960s, when he became an ......." }
The JSON has just the result key, no other keys
Basically I do not want to use anything other than plain HTML and JavaScript. I am a relative beginner to JavaScript and therefore I ask for commented code.
Here is one without using JQuery with pure JavaScript. I used javascript promises and XMLHttpRequest
You can try it here on this fiddle
HTML
<div id="result" style="color:red"></div>
JavaScript
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON('https://www.googleapis.com/freebase/v1/text/en/bob_dylan').then(function(data) {
alert('Your Json result is: ' + data.result); //you can comment this, i used it to debug
result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
You can do this with JSONP like this:
function insertReply(content) {
document.getElementById('output').innerHTML = content;
}
// create script element
var script = document.createElement('script');
// assing src with callback name
script.src = 'http://url.to.json?callback=insertReply';
// insert script to document and load content
document.body.appendChild(script);
But source must be aware that you want it to call function passed as callback parameter to it.
With google API it would look like this:
function insertReply(content) {
document.getElementById('output').innerHTML = content;
}
// create script element
var script = document.createElement('script');
// assing src with callback name
script.src = 'https://www.googleapis.com/freebase/v1/text/en/bob_dylan?callback=insertReply';
// insert script to document and load content
document.body.appendChild(script);
Check how data looks like when you pass callback to google api:
https://www.googleapis.com/freebase/v1/text/en/bob_dylan?callback=insertReply
Here is quite good explanation of JSONP: http://en.wikipedia.org/wiki/JSONP
Since it's an external resource you'd need to go with JSONP because of the Same origin policy.
To do that you need to add the querystring parameter callback:
$.getJSON("http://myjsonsource?callback=?", function(data) {
// Get the element with id summary and set the inner text to the result.
$('#summary').text(data.result);
});
If you want to use plain javascript, but avoid promises, you can use Rami Sarieddine's solution, but substitute the promise with a callback function like this:
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
And you would call it like this:
getJSON('https://www.googleapis.com/freebase/v1/text/en/bob_dylan', function(err, data) {
if (err != null) {
alert('Something went wrong: ' + err);
} else {
alert('Your Json result is: ' + data.result);
result.innerText = data.result;
}
});
You can use $.ajax call to get the value and then put it in the div you want to. One thing you must know is you cannot receive JSON Data. You have to use JSONP.
Code would be like this:
function CallURL() {
$.ajax({
url: 'https://www.googleapis.com/freebase/v1/text/en/bob_dylan',
type: "GET",
dataType: "jsonp",
async: false,
success: function(msg) {
JsonpCallback(msg);
},
error: function() {
ErrorFunction();
}
});
}
function JsonpCallback(json) {
document.getElementById('summary').innerHTML = json.result;
}
To display the Json data using Robin Hartman code. You need to add, the below line.
The code he gave gives you Object, object. this code retrieves the data in a better way.
result.innerText =JSON.stringify(data);
Since the desired page will be called from a different domain you need to return jsonp instead of a json.
$.get("http://theSource", {callback : "?" }, "jsonp", function(data) {
$('#summary').text(data.result);
});

JS to jQuery to the fullest

I have this:
function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
} else {
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
var nocache = 0;
function insert() {
document.getElementById('insert_response').innerHTML = "To Sek .. "
var bID= encodeURI(document.getElementById('bID').value);
var kommentar= encodeURI(document.getElementById('kommentar').value);
nocache = Math.random();
http.open('get', 'insert.php?bID='+bID+'&kommentar=' +kommentar+'&nocache = '+nocache);
http.onreadystatechange = insertReply;
http.send(null);
}
function insertReply() {
if(http.readyState == 4){
var response = http.responseText;
document.getElementById('insert_response').innerHTML = response;
if ($("#box[value=1]").length > 0) { window.parent.showMessage("Video Is OK"); }
}
}
And i want to "shorten" the code, and make it use jQuery to the fullest. eg, i have heard of serialize(); instead of using http.open etc.., but how should i use it in this case?
And do i really need all that in createobject() to make the http?
Untested, but I'm pretty sure this is what you need:
function onInsertComplete(data,textstatus){
$("#insert_response").html(data);
}
function doInsert(){
$("#insert_response").html("To Sek...");
var nocache = '0';
var data = { bID : $("#bID").val(), kommentar: $("#kommentar").val(), nocache: nocache };
$.get('insert.php', data, onInsertComplete);
if ($("#box[value=1]").length > 0) {
window.parent.showMessage("Video Is OK");
}
}
Most of this can be cleaned up with a call to the get method in jQuery.
First, it will abstract away the browser-specific details for you, so you don't have to check how get XMLHttpRequest.
You can then use jQuery to get elements through selectors. To select any element by id, you would use the following syntax:
$("#<id>")
The hashtag indicates that you want to select the elements with the id specified. From there you can use some of the general attribute functions to get the values inside of specific elements.
Finally, you can use Javascript's ability to generate closures to create and pass one as the callback to the get function, which is executed when the call completes. You would then use the same selectors general attribute functions to change the values on the client side when the call completes.
Something on this line?
http://api.jquery.com/load/
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});

Categories