Turning API data into HTML - javascript

sorry for the newbie question.
I'm new to using API's and I want to take the data from here
https://api.guildwars2.com/v2/commerce/prices/24615 (specifically the unit price under sells:) and display this in HTML.
This project will be using the unit price data across roughly 100 id's and I'd like to organize these numbers and run some basic math with them.
How can I go about this?
fetch('https://api.guildwars2.com/v2/commerce/prices/24615')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
So far I can get the data into the console, but I'm not sure how to turn this into something I can work with.

There is function in jQuery to make API calls, the following code makes you access api data,
$(document).ready( function() {
var info;
var whitelisted;
var quantity;
$.get("https://api.guildwars2.com/v2/commerce/prices/24615",function(obj){
info = obj['id'];
whitelisted = obj["whitlelisted"]
quantity = obj.buys['quantity']
$("#id1").html("id :"+info);
$("#whitelist").html("whitelisted :"+whitelisted);
$("#quan").html("quantity :"+quantity);
});
});
for more info you could look into the following pen link to the code

ignore these jerk moderators.
In your callback function, where you log myJson, edit your previously created html file,
like if you have a div, <div id="myDiv"> </div>, in the response function do something like this
const myDiv = document.getElementById("myDiv")
myDiv.textContent = myJson.name
And your div will show the name from json, or whatever you need. Play around with these ideas and you'll get far

Related

JS / JSON / JQuery - How to insert Data into Json file lil css

Today i want to create a page that:
inserts things from a json file into divs but also allows you to add new infos to that json.
also i wanted to create a like button with increasing counter and sort function based on the likes.
I dont know anything about php or ajax. its maybe possible to solve without it ?
look here is my code. its not working yet obviously :)
But i hope you get the idea. I basically think iam heading the right direction but just missing some pieces :)
For designing i did put a div which containts 2 divs // 1 for img and 1 for text. i later want to style it with css so that each row there will be 2 filmbox divs and with css flexbox i want wrap it so when windows gets smaller only 1 box each row.
Like i make .filmbox{ width: 40%;} so theres space for only 2 each row and the other things gets wrapped down
LAYOUT OF THE PAGE IMAGE LINK
// Copy Pastaed this ajax from internet to read json data from external file
let readJSON = function (file) {
let json = {}
$.ajax({
'async': false,
'global': false,
'url': file,
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
};
let film = readJSON("film.json")
console.table(film)
// Insert new Data to webpage
for (let i in film){
$(".content:eq("+i+")").append(`<div class="filmbox"><div class ="imgfield">
<img src="${film[i].img}" ></div>"<div class="textfield"> <h1>" + film[i].name + "</h1>
<br>" + film[i].description + "<br>" +
"<button type="button" id="button">LIKE</button>" + "<span id="likeCounter">
</span></div></div>`);
}
// Function to insert new Data into JSON from a from - Update website on Form click
let film = []
function getValues(){
let filmName = $(#fname).value;
let description = $(#fdescription).value;
let img = $(#fimg).value;
let filmData = [{
"name" : ${filmname},
"description" : ${description},
"img" : $${img}
}]
$(#formclick)on("click", ()=>{
**// how to insert to json file ?**
window.location.reload();
})
let counter = 0
// Like Button Function
$(#button).on("click", () =>{
$(#likeCounter).text(counter++)
)};
// SORT FUNCTION to first display films with the most likes
function orderDivs(){
counter.sort()
$(#button).find($counter) // Finds the value of likke button+
**Well and now sort all the Divs according to the like value the users did
input (it dont need to save the like value somewhere just when i like some films
on the page by randomly clicking like it then should sort the divs according to that**
}
$(#sortbutton).on("click", ()=>{
orderDivs()
})
To save the data to a JSON file you'd typically post the data to a server that has file system access (e.g. PHP or Node.js).
If you want to do this client-side, you could look at the FileSystem API, or persist the data in the browser with localStorage.
Regarding the like button / count increment / sorting, it would be better to post this as a separate, more specific question.

Showing single data field via Google Analytics API

I'm having trouble displaying only a single data field via the Google Analytics API.
For example, how would I display the number of users yesterday? Or the number of users in the past week?
I'm assuming "gapi.analytics.report.Data" is the right constructor. I've tried following the "Data" code in Google's Built-in Components Reference but nothing displays on the front-end.
For the "DataChart" code, there's a "container" option that references the HTML element in the DOM that will correctly display the chart.
This "container" option is missing in "Data" - so how do I display a single data field?
EDIT: Here's the code I'm working with.
You can see a pastebin of my code here: https://pastebin.com/M6U0Bd8B
There's also a live staging version of the site here: http://madebychris.ca/dashboard2.html
The first four section ids are all displaying properly but nothing's showing up for the final <p class ="report">
If you are trying to access the raw data numbers, you can just access the response object:
// Set up the request
var report = new gapi.analytics.report.Data({
query: {
ids: 'ga:XXXX',
metrics: 'ga:sessions',
dimensions: 'ga:city'
}
});
// Define what to do with the response data.
report.on('success', function(response) {
console.log(response);
});
// Run the report
report.execute();
For example, the total's for the metrics is response.totalsForAllResults and the rows for each dimension are held in response.rows
You need to select what you want to do with the variables on the report.on("success", function(response){ function. For example:
report.on('success', function(response) {
$("body > main > div > section:nth-child(4) > h2")[0].innerText =
response.totalsForAllResults["ga:sessions"]
});
report.execute();
Note: You should be able to test on the embedded API demo. Copying and pasting the initial code with the console.log should help show what is going on.

Simple auto-completion function in javascript

I am trying to get a simple auto-complete function to work based off the usernames that a 3rd party app provides.
The app outputs data in this general format:
"{
"UserA":{"IP":"XXX.XXX.XXX.XXX","ConnectTime":"/Date(1435769694510)/","LastAskSource":"","LastAskType":2,"Name":"UserA"},
"UserB":{"IP":"XXX.XXX.XXX.XXX","ConnectTime":"/Date(1435769694510)/","LastAskSource":"","LastAskType":2,"Name":"UserB"},
"UserC":{"IP":"XXX.XXX.XXX.XXX","ConnectTime":"/Date(1435769694510)/","LastAskSource":"","LastAskType":2,"Name":"UserC"}
}"
Now, I want to use the general auto-complete function listed below:
$("#chatEntryBox").autocomplete({
source: usersOnline.Name
});
I have defined the array as such:
OnlineUsers = data.userinfo;
for (var i in OnlineUsers) {
var user = OnlineUsers[i];
usersOnline = $.map(OnlineUsers, function(el) { return el; })
}
Now, this part above works the way I would expect. I can test in the console what the values are of the array by doing JSON.stringify(usersOnline[0].Name);
I have looked at the documentation on the website for Jquery... I just think I am missing something or misunderstanding. If someone could point me in the right direction that would be great.
The end goal would be typing the first few letters of the users name, and it auto-completing the rest.
I made a fiddle for your problem here.
Loop to take out names from json can be as simple as this
var usersOnline = $.map(input, function(el) { return el.Name; })
$( "#chatEntryBox" ).autocomplete({
source: usersOnline
});

Return arrays from meteor mongo

ajduke:bootstrap-tagsinput
I am using the above package to create a tags system. I have used <select multiple> from the True Input Value from the link above and have inserted each tags as Strings within the tag array.
This is what my db looks like.
Posts
tags //Array
[0] : sometag //String
[1] : sometag //String
[2] : sometag //String
//and so forth..
So my question is...
I want to return all the tags within a post to the following format, so that I can reuse it to show the tags when my users try to edit their posts.
Wanted Format
['sometag', 'sometag', 'sometag', and so forth]
Edit1
this is what I've done so far.
Post_Edit.js
Template.postEdit.rendered = function() {
myTags = Posts.findOne({_id: this._id}).tags.fetch(); //AAA
$('.tagsinput').tagsinput('add', myTags); //From above link API
}
I've tried other methods for //AAA line but I am having no luck.I've tried things such as Posts.findOne.map... Maybe my english comprehension is not up to par but the documentations in meteor did not help me understand any better.
Edit 2
Posts.findOne({_id: "ziZw3wLaxFyz3DYP4"}).tags
I've tried putting this in the browser console and got the array in the format that I wanted.
But the problem is, it won't work in my app when I use it.
When I use Posts.findOne({_id: this._id}).tags in my postEdit.rendered, I get this browser console error. Cannot read property 'tags' of undefined
Post_Edit.js
Template.postEdit.rendered = function() {
myTags = Posts.findOne({_id: this._id}).tags;
$('.tagsinput').tagsinput('add', myTags); //From above link API
}
What I don't understand is why is it working in browser console but not my Template.postEdit.rendered?
You are correct that your variable myTags is undefined when Template.postEdit.rendered is called because the Posts database has not finished loading when your function is called.
myTags = Posts.findOne({_id: this._id}).tags.fetch(); //AAA
Solution
There are multiple strategies including:
Updating DOM after subscription completes
http://docs.meteor.com/#/full/Blaze-TemplateInstance-subscribe
Re-run the function when Collection changes
http://docs.meteor.com/#/full/tracker_autorun
Template.postEdit.rendered = function() {
Tracker.autorun(function () { ** NEW LINE **
myTags = Posts.findOne({_id: this._id}).tags;
$('.tagsinput').tagsinput('add', myTags);
} ** NEW LINE **
}
I've approached a completely different way to figure this out.
But I'd still like to know why my method did not work...
post_edit.js
Template.postEdit.helpers({
tags: function(){
Posts.findOne({_id:this._id}).tags;
}
});
post_edit.html
<select class=tagsinput id="tagsinput" data-role="tagsinput">
{{#each}}
<option value="{{this}}">{{this}}</option>
{{/each}}

JQuery Autocomplete GET & JSON array data security concerns

I am learning JQuery with a MVC3 book. I find that Json data is really easy to use, but it may not be safe.
Consider the scenario, say, I got a CRM with senstive customer infomation. Ajax returns Json array as search results. The search textbox ajax autocomplete also return Json array of senstive keywords from database. etc...They all use GET method.
However, it is said that GET method has vulnerabilities when passing around Json array data:
http://haacked.com/archive/2009/06/25/json-hijacking.aspx
http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
How do you JQuery experts out there go about fixing this issue? Please help.
--- EDIT: ---
#Gren. Awesome. Thank you. Based on your tips, here is what I figured out.
The normal autocomplete returning json array
and a mod one with a json object wrapping the array
Here is the code, assuming we got a global List named txtlst in the controller.cs...
// normal one
public JsonResult AutoCompleteHelper1(string term) {
//if (!Request.IsAjaxRequest()) return null;
var lst = txtlst.Where(s => s.StartsWith(term)).ToList();
var res = lst.Select(x => new { value = x }).ToList();
return Json(res, JsonRequestBehavior.AllowGet);
}
//mod one
public JsonResult AutoCompleteHelper2(string term) {
//if (!Request.IsAjaxRequest()) return null;
var lst = txtlst.Where(s => s.StartsWith(term)).ToList();
var res = lst.Select(x => new { value = x }).ToList();
return Json(new { wrapper= res, name="wrapper" }, JsonRequestBehavior.AllowGet);
}
}
and then in the .cshtml file...
<p>Auto Complete Example</p>
<input type="text" name="q" id="MyInput1" data-autocomplete-source="#Url.Action("AutoCompleteHelper1", "Home")"/>
<input type="text" name="q" id="MyInput2" data-autocomplete-source="#Url.Action("AutoCompleteHelper2", "Home")" />
and then in the .js file...
$(document).ready(function () {
// normal autocomplete
$("#MyInput1").autocomplete({ source: $("#MyInput1").attr("data-autocomplete-source") });
// mod autocomplete with a wrap
$("#MyInput2").autocomplete({
source: function (req, add) {
$.getJSON($("#MyInput2").attr("data-autocomplete-source"), req, function (data) {
var suggestions = [];
$.each(data.wrapper, function (i, o) {
suggestions.push(o.value);
});
add(suggestions);
});
}
});
});
--- EDIT 2: ---
Please ignore those comments that are telling me to use POST. They
are not reading the blog links or do not understand the issue.
The other option is to wrap your JSON Arrays within JSON objects. The article and comments in it answered this question.
Edit:
From the article:
The fact that this is a JSON array is important. It turns out that a script that contains a JSON array is a valid JavaScript script and can thus be executed. A script that just contains a JSON object is not a valid JavaScript file.
If you wrap your json array in an object {"myJsonArray":[{"name":"sensitive"},{"name":"data"}]} the HTML script tag would not be able to execute.
Security of an Ajax/JSONP/JSON call is the same exact thing as the security of an http call since Ajax requests are http requests. Nothing changes in how you handle it. You make sure the user is logged in and can access the information.
If you are worried about data being cached, use Post or set the proper no caching headers with the backend.
EDIT:
Things you can do to prevent JOSN from being read is the infinite loop trick. Stick an infinte loop in front of the call, means your Ajax call will have to strip this before using it.
You can use keys, third party site would not have the keys needed to validate the request.
You can check referrers.

Categories

Resources