Haven't touched Javascript for a bit while and cannot find a proper way to extract data from a JSON object.
So I am basically sending a simple GET request to the Giphy API and attempting to get URL's from the response but for some reason I get all kinds of errors.
This is what I tried:
$(function() {
$('#searchButton').click(function() {
console.log("test");
$("#result").append("test<br />");
var xhr = $.get("http://api.giphy.com/v1/gifs/search?q=cats&api_key=dc6zaTOxFJmzC&limit=1");
xhr.done(function(data) {
console.log(this.fixed_height);
$("#result").append("success got data<br />" + data + "<br />");
console.log("success got data", data);
$.each(data.results, function() {
$.each(this.images, function() {
console.log(this.fixed_height);
$("#result").append(this.fixed_height + "<br />");
});
})
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="searchButton">search!</button>
<div id="result"></div>
You have a couple of problems. First, there is not a results member in the data object. The only thing I see that you can iterate on, in the data object is yet another data member. Second, inside the images, there is no fixed_height, just height. This works:
var xhr = $.get("http://api.giphy.com/v1/gifs/search?q=cats&api_key=dc6zaTOxFJmzC&limit=1");
xhr.done(function (data) {
$.each(data.data, function () {
$.each(this.images, function () {
console.log(this.height);
});
})
});
http://jsfiddle.net/n9ffva83/
Remember $(function () {});is not needed in JSFiddle, so you must provided (just the way you do in the code you gave us above).
EDIT:
To just get the url of the fixed height try this:
var xhr = $.get("http://api.giphy.com/v1/gifs/search?q=cats&api_key=dc6zaTOxFJmzC&limit=1");
xhr.done(function (data) {
$.each(data.data, function () {
console.log(this.images.fixed_height.url);
})
});
It seems this url is only one, that belong to the images.
http://jsfiddle.net/n9ffva83/1/
Related
I just created a Google sheet document and converted it to JSON-file.
Sheet: https://docs.google.com/spreadsheets/d/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/edit#gid=0
JSON: https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic?alt=json
Now, on the sheet I have text on cells A1 and A2.
I would like to display these lines on HTML-document.
Would somebody know how I can do this?
I think something is wrong at your JSON file, because Line 1 is missing, but based on your json here is how you can access the text:
const jsonResult = {"version":"1.0","encoding":"UTF-8","feed":{"xmlns":"http://www.w3.org/2005/Atom","xmlns$openSearch":"http://a9.com/-/spec/opensearchrss/1.0/","xmlns$gsx":"http://schemas.google.com/spreadsheets/2006/extended","id":{"$t":"https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic"},"updated":{"$t":"2020-01-09T13:49:33.116Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"Taulukko1"},"link":[{"rel":"alternate","type":"application/atom+xml","href":"https://docs.google.com/spreadsheets/d/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/pubhtml"},{"rel":"http://schemas.google.com/g/2005#feed","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic"},{"rel":"http://schemas.google.com/g/2005#post","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic"},{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic?alt\u003djson"}],"author":[{"name":{"$t":"contact.tjolanki"},"email":{"$t":"contact.tjolanki#gmail.com"}}],"openSearch$totalResults":{"$t":"1"},"openSearch$startIndex":{"$t":"1"},"entry":[{"id":{"$t":"https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic/cokwr"},"updated":{"$t":"2020-01-09T13:49:33.116Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"Line2"},"content":{"type":"text","$t":""},"link":[{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic/cokwr"}]}]}}
const entries = jsonResult.feed.entry;
entries.forEach(function (arrayItem) {
const titleObj = arrayItem.title
const text = titleObj['$t'];
console.log("title object: " + JSON.stringify(titleObj, null, 2))
console.log("Text: " + text)
document.getElementById("result").innerHTML += text;
});
<div id="result"> Text: </div>
You can use json-pretty-print to see the json more clearly.
EDIT
I don't know if the json link is updated real time when you modify the sheet but you can do this:
Make a call to your json link with $.ajax({ type: "GET".. }) in order to retrieve the whole object that I pasted in the previews snippet (Read more about request from here jquery.get )
Make a callback function in order get the content after the request is finished (Read more about callbacks from Callback_function )
Apply the function who print the text
const jsonURL = "https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic?alt=json"
function printTextFromJson(json) {
const entries = json.feed.entry;
entries.forEach(function(arrayItem) {
const titleObj = arrayItem.title
const text = titleObj['$t'];
console.log("title object: " + JSON.stringify(titleObj, null, 2))
console.log("Text: " + text)
document.getElementById("result").innerHTML += text;
});
}
function getJsonContent(callbackFunction) {
$.ajax({
type: "GET",
url: jsonURL,
success: function(returnValue) {
console.log(returnValue);
callbackFunction(returnValue); // callbackFunction is called when returnValue is ready.
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
},
dataType: "json"
});
}
getJsonContent(function(returnValue) {
printTextFromJson(returnValue)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"> Text: </div>
Sorry if the answer is a bit too complex, but everything has a start. If you have questions feel free to ask! xD
PS: try to change the sheet and run this snippet again, if it's not updating, then the two files are not in sync.
You have to import the .json-file in your js-code as an object. Then you can access to each value like you would with an "normal" object.
object.parameter
I recently came across the Yify-torrents api at YifyTorrentAPI and just thought let's give it a try with jquery and create a little own application. I used the following code to retrieve the upcomming movies list which worked.
$.getJSON("https://yts.re/api/upcoming.json", function(data) {
$.each(data, function(item, value) {
console.log(value.MovieTitle + ' ' + value.ImdbLink);
});
});
on the other side when I tried to get all the movies list using the following request I just got undefined in the console.
$.getJSON("https://yts.re/api/list.json", function (data) {
$.each(data, function (item, value) {
console.log(value.MovieTitleClean + ' ' + value.ImdbLink);
});
});
I am sharing the Fiddle in which I have wrote the code. Any help will be appreciated. Thanks
The second ajax call is returning movies in a MoviesList object so you need to iterate on data.MovieList not data.
JSON:
{
"MovieCount":4921,
"MovieList":
[{
"MovieID":"5372",
"State":"OK",
"MovieUrl":"https:\/\/yts.re\/movie\/Gun_Woman_2014_1080p",
"MovieTitle":"Gun Woman (2014) 1080p","MovieTitleClean":"Gun Woman",
"MovieYear":"2014",
"DateUploaded":"2014-06-30 00:10:03",
"DateUploadedEpoch":1404043803,
"Quality":"1080p",
"CoverImage":"https:\/\/static.yts.re\/attachments\/Gun_Woman_2014_1080p\/poster_med.jpg",
"ImdbCode":"tt3141912",
"ImdbLink":"http:\/\/www.imdb.com\/title\/tt3141912\/",
"Size":"1.24 GB",
"SizeByte":"1335275815",
"MovieRating":"8.2",
"Genre":"Action",
"Uploader":"OTTO",
"UploaderUID":"310615",
"Downloaded":"35173",
"TorrentSeeds":"20",
"TorrentPeers":"24497",
"TorrentUrl":"https:\/\/yts.re\/download\/start\/777FD07DAD285CB06846CAFD97600B07F2CC88B3.torrent",
"TorrentHash":"777fd07dad285cb06846cafd97600b07f2cc88b3",
"TorrentMagnetUrl":"magnet:?xt=urn:btih:777fd07dad285cb06846cafd97600b07f2cc88b3&dn=Gun+Woman&tr=http:\/\/exodus.desync.com:6969\/announce&tr=udp:\/\/tracker.openbittorrent.com:80\/announce&tr=udp:\/\/open.demonii.com:1337\/announce&tr=udp:\/\/exodus.desync.com:6969\/announce&tr=udp:\/\/tracker.yify-torrents.com\/announce"
}]
}
do like this:
$.getJSON("https://yts.re/api/list.json", function (data) {
console.log("Getting all the movies");
// console.log(data)
$.each(data.MovieList, function (item, value) {
console.log(value.MovieTitleClean + ' ' + value.ImdbLink);
});
});
UPDATED FIDDLE
I want to send json data from my controller to my view when a specific action happens.
I used this on controller to send the data
[HttpGet]
public JsonResult JSONGetParking(int buildingID){
return this.Json(
new
{
Result = (from obj in db.Parkings.Where(p => p.buildingID == buildingID) select new { ID = obj.ID, Name = obj.note })
}
, JsonRequestBehavior.AllowGet
);
}
it works very good
on my script i used this:
FloorScript.js
$(document).ready(function () {
$('#buildingID').change(function () {
alert("what is not");
$.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
alert("afd");
var items = " ";
$.each(data, function (obx, oby) {
items += "<option value='" + oby.ID + "'>" + oby.Name + "</option>";
});
$('#parkingID').html(items);
});
});
});
I have opened google chrome and I can see the request and the response like this:
i can see the two text that i alerted
However, on my selector, i just see undefined value
Html
<div id="editor-label">
<select id="parkingID" name="parkingID"></select>
</div>
I have added the jquery in this
#section scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/FloorScript.js");
}
You're not looping on the correct variable.
You did this:
$.each(data, function (obx, oby) {
whereas you should do this:
$.each(data.Result, function (obx, oby) {
This is pretty visible in the Google Chrome screenshot you provided. As you can see the returned JSON has a property called Result which is the collection whereas you were looping over the data variable which is not an array - it's just a javascript object that has a property called Result which is the array you wanna be looping through.
Also I'd replace:
$.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
with:
$.getJSON('JSONGetParking', { buildingID: $('#buildingID').val() }, function (data) {
and of course get rid of this hardcoded url over there and use an url helper to generate it, on the dropdown as an HTML5 data-* attribute:
#Html.DropDownListFor(
x => x.BuildingId,
Model.Buildings,
new {
id = "buildingID",
data_url = Url.Action("JSONGetParking")
}
)
and then inside the change event you can trivially easy retrieve this url and avoid hardcoding it (and of course taking the risk of breaking your code when you deploy it in IIS in a virtual directory or simply change the routing pattern of your application):
$('#buildingID').change(function () {
var url = $(this).data('url');
$.getJSON(url, { buildingID: $('#buildingID').val() }, function (data) {
Alright, now the initial mess is tidied up.
use data.Result in your each loop
$(document).ready(function () {
$('#buildingID').change(function () {
alert("what is not");
$.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
alert("afd");
var items = " ";
$.each(data.Result, function (obx, oby) {
items += "<option value='" + oby.ID + "'>" + oby.Name + "</option>";
});
$('#parkingID').html(items);
});
});
});
Hope this helps...
So, the Javascript code which can be found below doesn't seem to be functioning properly.
The goal is to get the text below the map to change on hover of the rooms.
Map Page
The JSON (zadias.me/SVG/rooms.json) data that pulls the data seems to be where I'm faulting, I think. When I test/debug the code by placing .innerHTML statements that would print in the text field, it would work if I placed the .innerHTML before the $.ajax, however, if I put the .innerHTML function in the "success" part of the .ajax, it wouldn't work..
Javascript:
$(document).ready(function(){
var json = (function () { //this function obtains the data
var json = null;
$.ajax({
'async': false,
'global': false,
'url': 'http://zadias.me/SVG/rooms.json',
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
function hashTag(){
var hashTag, hash2;
hashTag = location.hash; //obtains the part of the URL with the hash tag and what follows
hashTag = hashTag.replace(/#*/, ''); //replaces the hash tag
if(hashTag.length > 0){
for(i=0 ; i<json.rooms.length ; i++){
if (json.rooms[i].roomId == hashTag) //linear search through array of rooms to see if any equal the hashTag
{
document.getElementById('room_info').innerHTML = '<img src="images/' + json.rooms[i].image + '" /><h4>' + json.rooms[i].name + '</h4>' + json.rooms[i].HTMLdescrip;
} //loads the data from the JSON data.
}
}
};
function setHash(){
window.location.hash = this.id; //creates the hash link based on the object's id (object id acquired from the JSON data) and sets it
};
function setHTML(){
for(i=0 ; i<json.rooms.length ; i++){
if (json.rooms[i].roomId == this.id)
{
document.getElementById('room_info').innerHTML = '<img src="images/' + json.rooms[i].image + '" /><h4>' + json.rooms[i].name + '</h4>' + json.rooms[i].HTMLdescrip;
}
}
};
window.onload = hashTag();
$(".active").click(setHash);
$(".active").mouseenter(setHTML);
//$(".active").mouseover(setHTML);
$(".active").mouseleave(hashTag);
});
I understand that it's a bit localized, how could I change this up?
If I'm getting it right, you need the variable json to be global. Just take off the var at the beginning and see if that helps.
You may want to try something more along these lines:
// this returns a promise
var json,
response = $.ajax({
'async': false,
'global': false,
'url': 'http://zadias.me/SVG/rooms.json',
'dataType': "json",
'success': function (data) {
json = data;
}
});
window.onload = function() {
// ensures that the ajax has returned a value
response.done(hashTag);
};
The document doesn't really have to be ready for you to run an AJAX request.
You may want to take a look here for accessing the SVG elements: How to access SVG elements with Javascript. Requires a change from <embed> to <object>
Here's a version of your code with a few updates:
var json;
$(document).ready(function(){
$.ajax({
'global': false,
'url': 'http://zadias.me/SVG/rooms.json',
'dataType': "json",
'success': function (data) {
json = data;
hashTag();
$(".active")
.click(setHash)
.mouseenter(setHTML)
.mouseleave(hashTag);
}
});
});
function hashTag(){
//get everything in the URL after the #
var hash = location.hash.replace(/#*/, '');
if(hash.length > 0){
//linear search through array of rooms to find the hashTag
$.each( json.rooms, function( room ) {
if (room.roomId == hash) {
$('#room_info').html(
'<img src="images/' + room.image + '" /><h4>' +
room.name + '</h4>' + room.HTMLdescrip
);
} //loads the data from the JSON data.
});
}
};
// creates the hash link based on the object's id
// (object id acquired from the JSON data) and sets it
function setHash(){
window.location.hash = this.id;
}
function setHTML(){
$.each( json.rooms, function( room ) {
if (room.roomId == this.id) {
$('#room_info').html(
'<img src="images/' + room.image + '" /><h4>' +
room.name + '</h4>' + room.HTMLdescrip
);
}
});
}
What I changed:
Made the json variable global.
Removed the async:true. Never use that!
Removed global:false. You don't have any global Ajax event handlers, so this flag has no effect.
Removed unnecessary quotes around the $.ajax() property names.
Removed the event handler setup at the end of the code.
Moved that initialization inside the $.ajax() callback since that is when the data is ready.
Chained together the event handler setup on $(".active") instead of repeating the selector call.
Used $.each() instead of the for loops for simplicity.
Changed the json.rooms[i] references to room thanks to $.each().
Used $('#foo').html(html) instead ofdocument.getElementById()and.innerHTML`, again for simplicity.
Simplified the setup of the hashTag variable and changed its name to hash to avoid confusion with the function name.
Removed unnecessary semicolons at the end of function definitions.
Made the indentation and formatting more consistent.
Shortened the excessive line lengths.
Some of these changes are just stylistic, but they're things I recommend. Naturally you can pick and choose among those after looking through the code.
The important point is making sure that the json data is available not just where it's needed, but when it's needed, and without using async:false.
How can I make this code work, the problem is that I can't seem to be able to acces the data returned, I know that it connects to the server, but for somereason it wont work, for example, I tried extracting the title but nothing appears.
$.ajax({
url : "https://www.googleapis.com/books/v1/volumes?q=harry+potter",
dataType : "jsonp",
async : true,
//if ajax call succeeds perform this action
success : function(result) {
ajax.parseJSONP(result);
},
//if there is an error to the ajax call perform this action
error : function(request, error) {
alert('Network error has occurred please try again!');
}
});
//parseJsonP and add new elements to list-view
var ajax = {
parseJSONP : function(result) {
//iterate each returned item
$.each(result, function(i, row) {
$('#listview_test').append('<li><h3>' + row.volumeInfo.title + '</h3></a></li>');
}); //end iteration of data returned from server and append to the list
$('#listview_test').listview('refresh'); // refresh the list-view so new elements are added to the DOM
}
}
My confusion is on the callback method, in their example Books API has a code like is shown down, but I dont get it this part q=harry+potter&callback=handleResponse, how can I make this while using the $.ajax method. Tried understanding all the pieces but still very confusing?
<body>
<div id="content"></div>
<script>
function handleResponse(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
// in production code, item.text should have the HTML entities escaped.
document.getElementById("content").innerHTML += "<br>" + item.volumeInfo.title;
}
}
</script>
<script src="https://www.googleapis.com/books/v1/volumes?q=harry+potter&callback=handleResponse"></script>
</body>
Try replacing your following code:
$.each(result, function(i, row) {
for this one:
$.each(result.items, function(i, row) {
As per the google example code the data is located in an array called items within the returned object.