What's wrong with my .each() function - ajax

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.

Related

Knockout: How to put $.get into a function?

I am using getJSON in my knockout view:
$.getJSON("/GetItems", function (data) {
self.Items(data.map(viewModelFromData));
});
I want to make it a function for reuse so next time I can reload items on page action. How to do it?
When I tried:
self.getBasketItems = $.getJSON("/umbraco/Surface/Booking/GetBasketItems",
function(data) {
self.Items(data.map(viewModelFromData));
// or return data.map(viewModelFromData);
});
I got self.getBasketItems() is undefined.
The quickest fix:
self.getBasketItems = function() {
return $.getJSON(
"/umbraco/Surface/Booking/GetBasketItems",
function(data) {
self.Items(data.map(viewModelFromData));
});
};
This returns the promise, so you can use it in a chain like so:
self.getBasketItems().then(function() { console.log(self.Items()); })
You can also make a more general utility function like:
const getTransformWrite = (url, converter, target) =>
() =>
$.getJSON(url)
.then(converter)
.then(target);
}
}
self.getBasketItems = getTransformWrite(
"/umbraco/Surface/Booking/GetBasketItems",
data => data.map(viewModelFromData),
self.Items
);
I don't really think this is an improvement, but it might suit your style.
Make sure you don't forget to handle exceptions/errors!
what #haim770 suggested was this:
self.getBasketItems = function() {
return $.getJSON(
"/umbraco/Surface/Booking/GetBasketItems",
function(data) {
self.Items(data.map(viewModelFromData));
});
};
But, from your comments, it seems you're trying to actually return the value into self.getBasketItems? In that case, you will need to do a synchronous call (getJSON is asynchronous) using the $.ajax method instead.
self.getBasketItems = function() {
var _r;
$.ajax(
dataType: "json",
async: false,
url: "/umbraco/Surface/Booking/GetBasketItems",
success: function(data) {
_r = self.Items(data.map(viewModelFromData));
});
return _r
};
Please note that this second solution is very quirky. And the browser will actually hang waiting for the response from the server. You would be better of using either callbacks or promises.
Let me know if this helps!
Cheers,

Trying to get data out of the youtube api

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.

Twitter Bootstrap Typeahead with JSON REST

I am having trouble implementing the Twitter Bootstrap Typeahead feature with a JSON web Service.
I have looked at all the examples on this website and can't find anything that will work. I know my JSON web service works; I can enter the address in my browser and it returns the JSON I expect with the MIME type set to "application/json".
I have this JavaScript in the
<body>
of my HTML page:
<script>
$('#typeahead').typeahead({
source: function (query, process) {
return $.getJSON(
'http://localhost:8732/IngredientsService/search/',
{ query: query },
function (data) {
return process(data);
});
}
});
</script>
I have this code as my "input":
<input type='text' id='typeahead' class='typeahead' data-provide="typeahead" data-items="10" />
Can anyone explain why this is not working?
According to the last comment ("web service not being accessed") - have you tried the more normal / documented approach?
$('#typeahead').typeahead({
source: function (query, process) {
return $.get('http://localhost:8732/IngredientsService/search/', { query: query }, function (data) {
return process(data.options); //if JSON is [ "options" : { ...}
});
}
});
$.getJSON is not nessecary, but useful when you want to load an entire JSON and inject potion of it as a source for the typeahead
$.getJSON("http://localhost:8732/IngredientsService/search/", function(json) {
$("#typeahead").typeahead({
source : json.options //again, dont know the structure of the JSON
});
});
From what I can see from the typeahead documentation, the source key in the parameters object is not valid.
It should look more like this I think:
$('#typeahead').typeahead({
remote: 'http://localhost:8732/IngredientsService/search/q=%QUERY'
});
http://jsfiddle.net/qVjsu/
It's better to omit return when using async sources because process() will be triggered twice
$('#typeahead').typeahead({
source: function (query, process) {
$.getJSON('/search/json/'+ query), function (data) {
return process(data);
});
},
minLength: 1,
items: 8
});

jqplot external data with async call?

Is there a way to load external data into jqplot with async call?
I want a live graph that updates every minute, but with async:false the page freezez every time when the data is recieving from server.
The reason it was done that way in the example was for simplicity's sake. The following is an async reworking of this:
var plot2 = null;
function fetchAjaxData(url, success) {
$.ajax({
url: url,
dataType:"json",
success: function(data) {
success(data);
console.log('loaded');
}
});
}
function createPlot(url) {
fetchAjaxData(url, function(data) {
if (plot2 == null) {
plot2 = $.jqplot('chart2', data, {
title: "AJAX JSON Data Renderer"
});
} else {
plot2.replot({data: data});
console.log('replotting');
}
});
}
$(document).ready(function(){
var jsonurl = "./jsondata.txt";
//Regenerate the plot on button click.
$('#ajax-button').click(function() {
createPlot(jsonurl);
});
//Generate the plot first time through.
createPlot(jsonurl);
});
And with HTML:
<div id="chart2" style="height:300px; width:500px;"></div>
<button id="ajax-button">Ajax retrieve</button>
So what this does is asynchronously fetch the data and plot it when the Ajax call succeeds. To keep it simple I am just reloading that same text file, though this could easily be adapted to scenarios where you are plotting a live data stream.

Uncaught TypeError: Object #<Object> has no method 'apply'

jQuery is throwing the following error:
Uncaught TypeError: Object # has no method 'apply'
f.event.dispatch
h.handle.i
I've found these related posts, but couldn't solve the problem using them:
This, this and this.
Here's the troublesome code:
$(document).ready(function(){
$('form.rating').click({
cancelShow:true,
callback: function(ui, type, new_value) {
var values = ui.$form.serializeArray();
values.push({
'name': 'rating',
'value': new_value
});
values = jQuery.param(values);
var msg = ui.$form.attr('update-msg');
$(msg).removeClass('hidden');
$(msg).show();
$(msg).find('div.msg-default').show();
$(msg).find('div.msg-result').hide();
$.ajax({
'type': 'POST',
'dataType': 'json',
'url': ui.$form.attr('action'),
'data': values
}).done(function(data) {
var overall_rating = ui.$form.attr('update-overall');
if(overall_rating && data['overall_rating']){
$(overall_rating).html(data['overall_rating']);
}
if(msg){
$(msg).find('div.msg-default').hide();
if(data['msg']) {
$(msg).find('div.msg-result').show();
$(msg).find('div.msg-result').html(data['msg']);
window.setTimeout(function() {
$(msg).addClass('hidden');
}, 2000);
} else {
$(msg).addClass('hidden');
}
}
if(data['user_rating'] && data['user_rating']>0) {
ui.select(parseInt(data['user_rating']));
}
});
}
});
});
Any ideas?
Edit: Okay, so I stripped it down to:
$(document).ready(function(){
$('form.rating').click({
});
});
And it is still showing the same error. Could this have something to do with my jQuery script? The only other info it shows is this line, but I don't think it helps much, since the file has 3 lines in total: jquery-1.7.2.min.js:3
The jquery click handler expects an anonymous function, like this:
$(document).ready(function(){
$('form.rating').click(function() {
// go for it!
});
});
#Ludder is close, but off by just a little. He's right that you need to be passing a function as the argument to click, but it doesn't have to be anonymous.
a = {myFun: function(){console.log("a");}}
$(document).ready(function(){
$('body').click(a.myFun);
});
and
b = function(){console.log("b");}
$(document).ready(function(){
$('body').click(b);
});
and
function c () {console.log("c");}
$(document).ready(function(){
$('body').click(c);
});
All log their bit of the alphabet. You were passing an empty object to click, give it a function instead.

Resources