I'm trying to populate an array in JavaScript using an anonymous function in the jQuery getJSON() function as follows.
$(document).ready(function() {
function Link(url, title) {
this.url = url;
this.title = title;
}
var links = [];
$.getJSON("http://reddit.com/r/programming/.json?jsonp=?", function(data) {
$.each(data.data.children, function(i, item) {
var title = item.data.title;
var url = item.data.url;
links.push(new Link(url, title));
})
});
for(var i=0; i< links.length; i++) {
var output = "<a href='" + k + "'>" + links[k] + "</a>";
$('<p>' + link + '</p>').appendTo('#content');
}
});
But, when I hit the for loop, the links array shows up empty. What's going on here?
Try that :
$(document).ready(function() {
function Link(url, title) {
this.url = url;
this.title = title;
}
$.getJSON("http://reddit.com/r/programming/.json?jsonp=?", function(data) {
var links = [];
$.each(data.data.children, function(i, item) {
var title = item.data.title;
var url = item.data.url;
links.push(new Link(url, title));
})
for(var i=0; i< links.length; i++) {
var output = "<a href='" + k + "'>" + links[k] + "</a>";
$('<p>' + link + '</p>').appendTo('#content');
}
});
});
Your loop was probably executed before your callback ;)
That's because $.getJSON is an asynchronous method. The code execution continues even after $.getJSON and reaches the for loop, by which time, your async request hasn't completed yet. You should move the loop within $.getJSON.
This jsFiddle http://jsfiddle.net/cArYg/2/ shows the iteration occuring before the getJson callback
Related
on line 30 i am facing an issue with $.each(data.menu, function (). I am being told by the console that "data is null". can anyone explain whats going on? thanks
function getFoodMenuData () {
var url = 'http://localhost:8888/Tom_Carp_Final_Project/Chorizios/foodMenu.json';
$.getJSON(url, function (data) {
window.localStorage.setItem('choriziosMenu333', JSON.stringify(data));
});
}
function showFoodMenuData () {
var data = JSON.parse(window.localStorage.getItem('choriziosMenu333'));
var images = "";
$.each(data.menu, function () {
images += '<li class="list-group-item"><img style="width: 100%;" src= "' + this.url + '"></li>';
images += '<li class="list-group-item">' + this.description + '</li>';
});
$('#foodMenu').append(images);
}
showFoodMenuData();
You have to call getFoodMenuData(), and then inside the callback for the asynchronous $.getJSON, call showFoodMenuData().
function getFoodMenuData() {
var url = 'http://localhost:8888/Tom_Carp_Final_Project/Chorizios/foodMenu.json';
$.getJSON(url, function(data) {
window.localStorage.setItem('choriziosMenu333', JSON.stringify(data));
showFoodMenuData(); // <--- call this inside the callback
});
}
function showFoodMenuData() {
var data = JSON.parse(window.localStorage.getItem('choriziosMenu333'));
var images = "";
$.each(data.menu, function() {
images += '<li class="list-group-item"><img style="width: 100%;" src= "' + this.url + '"></li>';
images += '<li class="list-group-item">' + this.description + '</li>';
});
$('#foodMenu').append(images);
}
getFoodMenuData(); // <--- call this first
I wouldn't use $ for the loop. I am not sure of the structure of the data you are receiving but you will probably need a nested loop to get all the data either way this should do the trick.
As a point the for in loop works great for objects. One reason is that the iterator is the key in the object. In this example if you console.log( ii ) inside the second loop you will see either name or url.
HTML
<ul></ul>
Javascript
var menu = {
item1 : {
name : "Food1",
url : "https://s-media-cache-ak0.pinimg.com/736x/79/82/de/7982dec0cc2537665a5395ac18c2accb.jpg"
},
item2 : {
name : "Food2",
url : "http://i.huffpost.com/gen/1040796/images/o-CANADIAN-FOODS-facebook.jpg"
}
};
$( document ).ready( function () {
for ( var i in menu ) {
for ( var ii in menu[ i ] ) {
var elem = ii === "name" ? "<p>" + menu[ i ][ ii ] + "</p>" : "<img src=" + menu[ i ][ ii ] + " height='100px'/>"
$( "ul" ).append( "<li>" + elem + "</li>" );
}
}
});
https://jsfiddle.net/dh3ozpxk/
I'm currently using the jQuery get method to read a table in another page which has a list with files to download and links to others similar webpages.
$.get(filename_page2, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find(target_element_type_page2 + '#' + target_element_id_page2)[0];
var container = document.getElementById(element_change_content_page1);
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var isFolder = table.getAttribute("CType") == "Folder";
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link = elem.getElementsByTagName("A")[0].getAttribute("href");
if (!isFolder) {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + link + "\">" + text + "</a></li>";
} else {
container.innerHTML += "<li class=\"folderlist\">" + "<a class=\"folderlink\" onclick=\"open_submenu(this)\" href=\"#\">" + text + "</a><ul></ul></li>";
var elem_page1 = container.getElementsByTagName("li");
var container_page1 = elem_page1[elem_page1.length - 1].getElementsByTagName("ul")[0];
create_subfolder(container_page1, link);
}
}
} else {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + "#" + "\">" + "Error..." + "</a></li>";
}
}, page2_datatype);
This is working fine, and all the folders and files are being listed. But when I try to do the same thing with the folders (calling the create_subfolder function) and create sublists with their subfolders and files, I'm getting a weird behavior.
function create_subfolder(container2, link1) {
$.get(link1, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find("table" + "#" + "onetidDoclibViewTbl0")[0];
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link2 = elem.getElementsByTagName("A")[0].getAttribute("href");
//nothing is changed in the webpage. The modifications in the html don't appear
container2.innerHTML += "<li>" + text + "</li>";
}
}
alert(container2.innerHTML); // Print the html with all the modifications
}, "html");
}
The second get(), inside the create_subfolder() function are not changing anything in the webpage, so no sublist is created. But, when I call the alert() function at the end of the get() function, it prints the code with all the modifications it should have made in the html at the second get callback. I believe the problem is related with the asynchronous behavior of the get function but I don't know exactly why. Any guess?
function Controles(contro, nomtab, numtab, action, nomcla, tipdat, lista, datos) {
$(document).on('click', '.'+contro+' #IZQTOD', function(event) {
$.getJSON(action+'&rows='+rows+'&page=1', function(datos) {
var nuevafila;
$.each(datos+tipdat, function(index, data) {
nuevafila = nuevafila + "<tr class='Fila-Grid-"+nomcla+"' id='" + numtab + (index + 1) + "'>";
nuevafila = nuevafila + "<td class='Columna1'>" + (index + 1) + "</td>";
var list = lista.split("-");
for (var j = 1; j < list.length; j++) {
nuevafila = nuevafila + "<td class='Borde-'>" + data+list[j] + "</td>";
}
nuevafila = nuevafila + "</tr>";
});
$('#'+nomtab+' tr:eq(1)').after(nuevafila);
});
});
}
I want to run this piece of code as a function of javascript in order to reuse code.
The part that does not work for me is the part of each:
$. each (+ tipdat data, function (index, data) {
Where "datos" is an object with variables (set and get) (codcli, name, apepat)
I mean to call codcli I do:
$. each (datos.codcli, function (index, data) {
}
But this way is static. I want to do through dynamic parameters.
So the question is how to pass parameters to successfully achieve? Or is that you can not do? There will always be static?
in the code above what I want to do is, but obviously does not work:
tipdat=".codcli"
$. each (datos+tipdat, function (index, data) {
}
I think you're looking for bracket notation.
var tipdat = "codcli";
$.each(datos[tipdat], function (index, data) {
//...
});
Is the same as:
$.each(datos.codcli, ...
If your string has multiple properties, I would do something like this:
var tipdat = "codcli.cod";
var objToIterate = datos;
var parts = tipdate.split('.');
for(var i = 0; i< parts.length; i++) {
objToIterate = objToIterate[parts[i]];
}
$.each(objToIterate, function (index, data) {
//...
});
I figured adding &outputSelector=GalleryInfo to the url would provide a higher resolution thumbnail, but that doesn't seem to work. I'm new to JSON, and the tutorial isn't very clear on the exact syntax to add to the URL to make this happen. Thanks!
<script>
function _cb_findItemsByKeywords(root)
{
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i)
{
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
if (null != title && null != viewitem)
{
html.push(
'<tr id="api_microposts"><td>'
+ '<img src="' + pic + '" border="0" width="190">' + '<a href="' + viewitem + '" target="_blank">' + title +
'</a></td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("api").innerHTML = html.join("");
// Define global variable for the URL filter
var urlfilter = "";
// Generates an indexed URL snippet from the array of item filters
function buildURLArray() {
// Iterate through each filter in the array
for(var i=0; i<filterarray.length; i++) {
//Index each item filter in filterarray
var itemfilter = filterarray[i];
// Iterate through each parameter in each item filter
for(var index in itemfilter) {
// Check to see if the parameter has a value (some don't)
if (itemfilter[index] !== "") {
if (itemfilter[index] instanceof Array) {
for(var r=0; r<itemfilter[index].length; r++) {
var value = itemfilter[index][r];
urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value ;
}
}
else {
urlfilter += "&itemFilter\(" + i + "\)." + index + "=" + itemfilter[index];
}
}
}
}
} // End buildURLArray() function
// Execute the function to build the URL filter
buildURLArray(filterarray);
url += urlfilter;
}
</script>
<!--
Use the value of your appid for the appid parameter below.
-->
<script src=http://svcs.ebay.com/services/search/FindingService/v1?SECURITY-APPNAME=*APP ID GOES HERE*&OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.12.0&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&sortOrder=PricePlusShippingLowest&paginationInput.entriesPerPage=6&outputSelector=GalleryInfo&outputSelector=AspectHistogram&itemFilter(0).name=Condition&itemFilter(0).value(0)=New&itemFilter(1).name=MaxPrice&itemFilter(1).value=450.00&itemFilter(1).paramName=Currency&itemFilter(1).paramValue=USD&itemFilter(2).name=MinPrice&itemFilter(2).value=350.00&itemFilter(2).paramName=Currency&itemFilter(2).paramValue=USD&itemFilter(3).name=ListingType&itemFilter(3).value=FixedPrice&keywords=Moto%20x%2016gb>
</script>
It seems like you're looking for the galleryPlusPictureURL: http://developer.ebay.com/Devzone/finding/CallRef/types/SearchItem.html#galleryPlusPictureURL
I am writing a game for Facebook. IN the following code, I have a problem. I have a for loop executing, and in that loop, I call a dialog and implement 'onconfirm' for the dialog. The problem is that I need to access th e loop counter inside of the onconfirm function. But because the onconfirm is called outside of the scope of the for loop, the counter value is no longer valid because it's been incremented. I need some way to pass the counter value to the dialog onconfirm as it was at the time the dialog was displayed, not after the loop has finished. Or maybe someone has a better solution. Any help would be appreciated. Thanks.
function unloadCargo() {
//debugger;
var actionPrompt = document.getElementById('action-prompt');
actionPrompt.setTextValue('Unloading cargo...');
var ajax = new Ajax();
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
debugger;
if(data.unloadableCargo.length == 0) {
loadCargo();
} else {
//console.log('unloadable cargo='+dump(data.unloadableCargo));
var i = 0;
var j = 0;
var ucCount = data.unloadableCargo.length;
for(i = 0; i < ucCount; i++) {
cargoDialog = new Dialog();
cargoDialog.showChoice('Unload Cargo', 'Unload ' + data.unloadableCargo[i].goods_name + ' at ' + data.unloadableCargo[i].city_name + ' for ' + data.unloadableCargo[i].payoff + 'M euros?');
cargoDialog.onconfirm = function() {
//console.log('unloadable cargo onconfirm='+dump(data.unloadableCargo));
var ajax = new Ajax();
var param = {"city_id": data.unloadableCargo[i].city_id, "goods_id": data.unloadableCargo[i].goods_id, "payoff": data.unloadableCargo[i].payoff};
ajax.ondone = function(demandData) {
var demands = document.getElementById('demands');
var innerXhtml = '<span>';
for(var j = 0; j < demandData.demands.length; j++) {
innerXhtml = innerXhtml + ' <div class="demand-item"><div class="demand-city">' + demandData.demands[j].city + '</div><div class="demand-pay">' + demandData.demands[j].cost + '</div><div class="demand-goods">' + demandData.demands[j].goods + '</div></div>';
}
innerXtml = innerXhtml + ' </span>';
demands.setInnerXHTML(innerXhtml);
// update balance
loadCargo();
}
ajax.post(baseURL + "/turn/do-unload-cargo", param);
}
cargoDialog.oncancel = function() { loadCargo(); }
}
//loadCargo();
}
}
ajax.post(baseURL + '/turn/unload-cargo');
}
You need to pass the value to the dialog somehow.
I have never looked at the FBJS, but it seems setContext can be used for that.
Try this:
cargoDialog = new Dialog().setContext({currentIndex: i});
// showChoice is the same
cargoDialog.onconfirm = function() {
alert(this.currentIndex); // Here you should be able to get it
}