Trying to get data out of the youtube api - ajax

So I'm trying to get data out of the youtube api with Ajax. I've tried the following method:
var url = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=2&playlistId=PL55713C70BA91BD6E&key=my_key';
$.getJSON(url, function (data) {
$.each(data, function () {
console.log(data);
});
});
As you can see I've got the url of a random playlist in var url. After that I'm looping through all of that data, and in the end I want to console.log all of the data. It's giving me the following data:
For some reason it's giving me all the data 5 times as you can see in the screenshot. Also, when I replace 'console.log(data)' by 'console.log(data.items.id)' it says the following in my console:
For some reason it's giving me all the data x5, and it also doesn't seem to be recognizing 'items'. Does anyone have any idea what went wrong in my code?

Maybe something along these lines would work:
var url = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=2&playlistId=PL55713C70BA91BD6E&key={YOUR-API-KEY}';
$.getJSON(url, function (data) {
data.items.forEach(function (item) {
console.log(item.snippet.title);
});
});
If you wanted to stick with using the jQuery each then you can do:
$.getJSON(url, function (data) {
$.each(data.items, function (key, value) {
console.log(value.snippet.title);
});
});
The each function is going to hand each of the items in the array into your function so you need the (key, value) signature so that you can access them in your iterator function.

Related

what alternative for ajax async deprecated feature?

Using the following ajax function to call an API endpoint which returns data in JSON format does not change the value of results from undefined to what ever is in the json['info'] but when changing async to false it does.
Inspecting the webpage containing this function it shows the this feature is deprecated and does not suggest anything else.
How do you read the json data with out writing more code to parse the data returned from the server?
function update_info()
{
var results ;
$.ajax({
type: 'GET',
url : "ip:port/api/info",
async:true,
success: function(data) {
results = data['info'];
//console.log(results);
}
});
console.log(results);
return results;
}
This does not seem to fit my goals as the data is returned from an API and not webpage source code is returned to the ajax.
As noted by David you should use asynchronous calls
function update_info()
{
return $.ajax({
type: 'GET',
url : "ip:port/api/info",
async:true,
success: function(data) { data;}
});}
async function f1() {
var results = await update_info();
console.log(results['info']);
}
f1();
this will return the ajax call when it is done and then you can grab the info data from it
You may use both approaches, and you can use .then or await.
I attached a source code for the following examples below.
ajaxRequest("https://httpbin.org/ip").then(result => {
console.log('Your PC Address is:' + result.origin);
});
let myPcRes = await ajaxRequest("https://httpbin.org/ip");
console.log('Your PC Address is from the await approach: ' + myPcRes.origin);
you need to compare the results to the $.ajax
and return the response from of success method.
I hope you will find it helpful,
https://jsfiddle.net/tru5k6qz/

JSON array within an array

im working with a JSON object here, i want to access the images, its an array within the array of 'results'. I know i have to loop, but not sure if im doing it correctly
My Code
function getVideos(art) {
$.ajax({
type: "GET",
url: 'http://imvdb.com/api/v1/search/videos?q=' + art,
dataType: 'json',
success: function (data) {
//alert(JSON.stringify(data.albums.name));
$('#videos').empty();
$.each(data.results.image, function (index, element) {
//alert(element.name);
$('#videos').append(element.results.image+ '<br/>');
});
},
error: function (data) {
$('#videos').html('<h3>Error in retrieval</h3>');
}
});
}
UPDATE when i just code
$.each(data, function (index, element) {
//alert(element.name);
$('#videos').append(element.results+ '<br/>');
});
i get
UPDATE:
it works for me now i just was accessing results instead of images
$.each(data.results, function (index, element) {
//alert(element.name);
$('#videos').append(element.image.o + '<br/>');
});
Your problem is in your $.each you already take it down to the level of data.results.image, and then you are looking for results.image within that. So to your jQuery script you are looking for every single data.results.image.results.image, and that doesn't exist. To loop through every results object, you need to do an $.each on data.results then look for element.image.
Here is a working JSFiddle which demonstrates this: http://jsfiddle.net/7udv3uoh/4/
UPDATE:
it works for me now i just was accessing results instead of images
$.each(data.results, function (index, element) {
//alert(element.name);
$('#videos').append(element.image.o + '<br/>');
});

What's wrong with my .each() function

I created an .getjson() call to work with reddit.com's API. The code is below.
$(document).ready(function() {
var SEARCH_URL = 'http://www.reddit.com/r/subreddits/search.json?jsonp=?';
var searchQueryText = 'XBox'; //getSearchQueryText();
$.getJSON(SEARCH_URL, {
q: searchQueryText,
limit: 3
})
.done(function (data) {
$.each(data.data.children, function(i,item) {
$("<h1>").attr("src", item.data.url).appendTo("#images");
});
})
.fail(function (data) {
alert("Something went wrong");
});
});//end ready
My .getJSON() function works and gets back data. However I am having trouble with my .each() function. I know it's slightly off even though my console isn't giving me an error message. I was hoping someone much smarter than me could help me rewrite it so it passes the content through #images in my body?
The JSON looks like this
http://www.reddit.com/r/subreddits/search.json?q=xbox&limit=3
If you just want to show all URLs in the #images elements, there is some problem in your code.
I test the reddit JSON data you're fetching.
The URL is a web page link not a image resource.
So why you try to add a non-exist attribute "src" to h1 element?
Try to use text() if you just want to show the URL and append them to element:
var SEARCH_URL = 'http://www.reddit.com/r/subreddits/search.json?jsonp=?';
var searchQueryText = 'XBox'; //getSearchQueryText();
$.getJSON(SEARCH_URL, {
q: searchQueryText,
limit: 3
})
.done(function (data) {
$.each(data.data.children, function(i,item) {
$("<h1>").text(item.data.url).appendTo("#images");
});
})
.fail(function (data) {
alert("Something went wrong");
});
This is jsfiddle demo
Hope this is helpful for you.

How to populate array with data returned from ajax call?

I'm making a call to an app to fetch data (routes), then looping through that data to fetch additional data about each individual route. The final data will show up in console.log without a problem, but I can't get it into an array.
$.getJSON('http://example-app/api/routes/?callback=?', function(data) {
var routes = [];
$(data).each(function(i){
routes.push(data[i]._id);
});
function getRouteData(route, callback) {
$.ajax({
url: 'http://example-app/api/routes/'+route+'?callback=?',
dataType: 'json',
success: function(data) {
callback(data);
}
});
}
var route_data = [];
$(routes).each(function(i) {
getRouteData(routes[i], function(data) {
console.log(data); // this shows me the 13 objects
route_data.push(data);
});
});
console.log(route_data); // this is empty
});
nnnnnn's right, you have to use Deferreds/promises to ensure that route_data is populated before sending it to the console.
It's not immediately obvious how to do this, with particular regard to the fact that $.when() accepts a series of discrete arguments, not an array.
Another issue is that any individual ajax failure should not scupper the whole enterprise. It is maybe less than obvious how to overcome this.
I'm not 100% certain but something along the following lines should work :
$.getJSON('http://example-app/api/routes/?callback=?', function(data) {
var route_promises = [];
var route_data = [];
function getRouteData(route) {
var dfrd = $.Deferred();
$.ajax({
url: 'http://example-app/api/routes/'+route+'?callback=?',
dataType: 'json'
}).done(function(data) {
//console.log(data); // this shows me the 13 objects
route_data.push(data);
}).fail(function() {
route_data.push("ajax error");
}).then(function() {
dfrd.resolve();
});
return dfrd.promise();//By returning a promise derived from a Deferred that is fully under our control (as opposed to the $.ajax method's jqXHR object), we can guarantee resolution even if the ajax fails. Thus any number of ajax failures will not cause the whole route_promises collection to fail.
}
$(data).each(function(i, route) {
route_promises.push( getRouteData(route) );
});
//$.when doesn't accept an array, but we should be able to use $.when.apply($, ...), where the first parameter, `$`, is arbitrary.
$.when.apply($, route_promises).done(function() {
console.log(route_data);
});
});
untested
See comments in code.

Retain the context of JQuery ajax function

I have an old code which is dependant on JQuery 1.3.2 that uses the following ajax call
function ChangeContent(url, somepageobject) {
var xhrobj = $.ajax({
url: url,
context: somepageobject,
callback: doFurtherStuff,
success: function(data) {
somepageobject.html($(data));
this.callback.call(this.context[0], data, "ok"); // >> Code breaks here
}
});
return xhrobj;
}
Problem with the code above is that this.callback is null when I upgraded to JQuery 1.8.1, most importantly the ChangeContent function is being used in different places and is outside my control (its used as as an API for external users...etc). An example of the usage of the above is like this:
xhr_object = ChangeContent("/someurl, $("#resultContainer"));
function doFurtherStuff(responseText, statusText, XMLHttpRequest)
{
var identifier = '#' + this.id;
...
}
Notice that the doFurtherStuff must have the correct "this" object value which is the context specified in ChangeContent function. When I tried to use different deferred then() ...etc. functions in JQuery 1.8.1 to solve the above this.callback.call(this.context[0], data); problem after the upgrade the "this" object in the callback function had different value since I guess the new JQuery library handles that differently.
Is there anyway to fix the error above while limiting the change to ChangeContent function only as I try to avoid asking all users to change the way they call and handle call backs from that function?
When you add the context option, you are telling jQuery what this should be inside of the success callbacks. That means you can't access the options passed into the ajax request. Either don't supply a context, or pass in the callback manually.
function ChangeContent(url, somepageobject) {
var callback = doFurtherStuff;
var xhrobj = $.ajax({
url: url,
context: somepageobject,
success: function(data) {
somepageobject.html($(data));
callback.call(this[0], data, "ok"); // >> Code breaks here
}
});
return xhrobj;
}
Update:
If you want to instead continue using your code as-is, simply rename the context property.
function ChangeContent(url, somepageobject) {
var xhrobj = $.ajax({
url: url,
thecontext: somepageobject,
callback: doFurtherStuff,
success: function(data) {
somepageobject.html($(data));
this.callback.call(this.thecontext[0], data, "ok"); // >> Code breaks here
}
});
return xhrobj;
}

Resources