Undefined variable error when parsing json - javascript

I'm trying to parse the json grabbed from here. Basically what I do is iterate over the items, sort them, then display them. But I get an error saying data.data.children[i] is undefined.
I can't think why it's doing it though?
var json = 'http://www.reddit.com/reddits/mine/.json';
GM_xmlhttpRequest({
method: "GET",
url: json,
onload: reddits
});
function reddits(response){
var txt = response.responseText;
var data;
var suggested = document.getElementById('suggested-reddits');
if(window.JSON && JSON.parse){
data = JSON.parse(txt);
}
else{
data = eval("("+txt+")");
}
suggested.innerHTML += '<span>reddits you\'re subscribed to </span> <ul id="rsub"></ul>';
GM_addStyle('#rsub{width: 500px;}');
var reddits = new Array();
var rsub = document.getElementById('rsub');
for(i = 0; i <= data.data.children.length; i++){
var r = data.data.children[i].data.display_name;
reddits.push(r);
}
sort(reddits);
for(i = 0; i <= reddits.length; i++){
rsub.innerHTML += '<li>' + reddits[i] + '</li>';
}
}

for(i = 0; i <= data.data.children.length; i++){
var r = data.data.children[i].data.display_name;
reddits.push(r);
}
Clear problem is in the for statement. Change the i <= data.data.children.length to i < data.data.children.length. Note the inequality change.
Since arrays in Javascript are 0-indexed, the element at i = data.data.children.length does not exist.
You should probably do the same things for the reddits.length loop.

Related

Nested loop only rendering last indexed item using jquery appendPe

Performing an ajax call to a drinks api and I've nested a loop to pull the ingredients out and render them to the page. The nested loop consoles the ingredients correctly but when I use jquery to append the results to the page only the item in the last index is displayed. I know there are null values I was going to remove them with an if statement after I got them to show.
function displayDrinkData(drinkName) {
var queryURL = "https://thecocktaildb.com/api/json/v1/1/search.php?s=" + drinkName
$.ajax({
url: queryURL,
method: "GET"
}).then(function (response) {
console.log(response);
var results = response.drinks;
for (var i = 0; i < results.length; i++) {
console.log(results[i]);
var eachDrink = results[i];
var drinkDiv = $("<div>");
var drinkName = results[i].strDrink;
for (var k = 1; k < 16; k++) {
console.log(eachDrink['strIngredient' + k]);
var ingList = $("<ul>").text("Ingredients: " + eachDrink['strIngredient' + k])
}
var pOne = $("<p>").text("Drink name: " + drinkName);
var drinkInstructions = results[i].strInstructions;
var pTwo = $("<p>").text("Instructions: " + drinkInstructions);
var drinkImage = $("<img>");
drinkImage.attr("src", results[i].strDrinkThumb);
drinkDiv.append(pOne);
drinkDiv.append(ingList);
drinkDiv.append(pTwo);
drinkDiv.append(drinkImage);
$("#drinks-view").append(drinkDiv);
}
})
}
Because var ingList is inside loop, not appending, but creating a new one every time.
var ingList = $("<ul>");
for (var k = 1; k < 16; k++) {
console.log(eachDrink['strIngredient' + k]);
ingList.append($('<li>').text("Ingredients: " + eachDrink['strIngredient' + k]));
}
Declare variable outside loop, and append <li> for each element.

Multidimentioanal arrays in JavaScript values not appending

I am trying to add values in a multidimensional array in JavaScript, but it doesn't seem to work. I get "variable not defined" error in snippet but can't see any variable which is not defined.
Does anyone have any idea what's going wrong here?
Many Thanks,
Hassam
var abc = "11:00, 11:10, 12:20,12:30";
var split = abc.split(",")
var limits = new Array();
var alltimes = [[],[]];
//var split = ["11:00", "11:10", "12:20","12:30"];
var x = 0;
for (var i = 0; i < split.length -1 ; i++) {
limits.push(split[i]);
// alert(split.length );
if(i%2 === 1) // If odd value
{
alert(limits);
for (var j = 0;j<2; j++)
{
// alert(limits[j]);
alltimes[x][j] = limits[j];
}
limits.length = 0;
x++;
}
// alert(split.length + 2);
//
}
alert(alltimes);
// console.log(abc)
This is my JavaScript code
$(document).ready(function(){
$('.timepicker').click(function(){
var ajaxurl = 'Ajax.php',
data = {'action': 'Hassam'};
$.post(ajaxurl, data, function (response) {
// $('#timepicker').timepicker('option', 'disableTimeRanges', [abc]);
var split = response.split(",");
var x = 0;
for (var i = 0; i < split.length -1 ; i++) {
limits.push(split[i]);
alert(split.length );
if(i%2 === 1) // If odd value
{
for (var j = 0;j<2; j++)
{
// alert(limits[j]);
alltimes[x][j] = limits[j];
}
limits.length = 0;
x++;
}
alert(split.length + 2);
//
}
alert(alltimes);
// console.log(abc)
});
There is very simple solution to achieve what you want.
var split = ["11:00", "11:10", "12:20", "12:30"];
var alltimes = [];
while (split.length) {
alltimes.push(split.splice(0, 2));
}
console.log(alltimes);

Evaluating JSON dynamic name

I want to display a database value and build a bootstrap grid, building the bootstrap grid was easy however displaying the data isn't as easily built.
Normally I would call the items I wanted in the loop like this x[i].DIAG;. However I am building a dynamically variable name "s": var s = i*cNum+j so that I can call the item dynamically x[s].DIAG. When I display the value with console.log(s), I see the values I want. However, when I try output the data it breaks. Any suggestions would greatly be appreciated.
JSON example:
0: Object
DIAG:"Anaplastic"
DIAGID:13
Code:
function loadDiag(){
$.ajax({type: "GET"
, dataType: "json"
, url: "CFCs/lookUps.cfc"
, data: {method: "Diag_rlu"}
, success: function(data){
var x = data.items;
console.log(x)
var rNum = x.length / 6 //number of rows
var cNum = 6 // number of colums
var str = '';
for (var i = 0; i < rNum; i++) {
str += '<div class="row" id="'+i+'">';
for (var j = 0; j < cNum; j++) {
var s = i*cNum+j
if(s <= x.length){
str += '<div class="col-xs-2">'+x[s].DIAG+'</div>';
} else{
str += '<div class="col-xs-2"></div>';
}
}
str += '</div>';
}
$('.diagnosis').html(str);
}
});
}

Jquery ajax send json

Javascript:
function add_content(count)
{
var result = {};
var row = new Array();
for (i = 0; i < count; i++)
{
result['img_src'] = $("#img_" + i).attr('src');
result['desc'] = $("#desc_" + i).val();
row.push(result);
}
$.ajax({
url: "ajax-functions.php",
data: {json_data: JSON.stringify(row)},
type: 'post',
success: function (output) {
alert(output);
}
})
}
Php:
$img_desc = json_decode($_POST['json_data'],TRUE);
$count = count($img_desc);
echo 'count:'.$count;
print_r($img_desc);
I want to send json to from JS to PHP. This above code works well, but it send the last data of the for loop is set in all the objects.
How to fix it? Is this right way?
Thanks.
Push a new object on each round of the loop into to the array
for (var i = 0; i < count; i++) {
row.push({
"img_src": $("#img_" + i).attr('src'),
"desc": $("#desc_" + i).val()
});
}
fiddle
Move result declaration inside for:
var row = new Array();
for (i = 0; i < count; i++)
{
var result = {};
result['img_src'] = $("#img_" + i).attr('src');
result['desc'] = $("#desc_" + i).val();
row.push(result);
}
or it can be done more elegantly:
var row = new Array();
var result;
for (i = 0; i < 10; i++)
{
result = row[ row.push({}) - 1 ];
result['img_src'] = $("#img_" + i).attr('src');
result['desc'] = $("#desc_" + i).val();
}
You can make the keys of result array also dynamic
Since you are not making it dynmamic, its getting over ridden in the next loop
EDIT:
for (i = 0; i < count; i++)
{
var result = {};
result['img_src'] = $("#img_" + i).attr('src');
result['desc'] = $("#desc_" + i).val();
row.push(result);
}

nested javascript queries in parse

I have the code below. Basically I have 3 nested parse queries. One is getting a number of "followers" and for each follower I am getting a number of "ideas" and for each idea I would like to get that idea creator's name (a user in the user table).
The first two nested queries work but then when i try to get the name of the user (the creator of the idea), that last nested query DOES NOT execute in order. That query is skipped, and then it is executed later in the code. Why is this happening please?
var iMax = 20;
var jMax = 10;
var IdeaList = new Array();
var IdeaListCounter = 0;
var myuser = Parse.User.current();
var Followers = new Parse.Query("Followers");
Followers.equalTo("Source_User",{__type: "Pointer",className: "_User",objectId: myuser.id});
Followers.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
var Ideas = new Parse.Query("Ideas");
Ideas.equalTo("objectId_User", {__type: "Pointer",className: "_User",objectId: object.get('Destination_User').id});
Ideas.find({
success: function(results2) {
for (i=0;i<iMax;i++) {
IdeaList[i]=new Array();
for (j=0;j<jMax;j++) {
IdeaList[i][j]=0;
}
}
for (var j = 0; j < results2.length; j++) {
var object2 = results2[j];
var ideausername2 = "";
IdeaListCounter++;
var ideausername = new Parse.Query("User");
ideausername.equalTo("objectId",object2.get('objectId_User').id);
ideausername.first({
success: function(ideausernameresult) {
ideausername2 = ideausernameresult.get("name");
}
});
IdeaList[IdeaListCounter,0] = object2.get('objectId_User').id + " " + ideausername2; //sourceuser
IdeaList[IdeaListCounter,1] = object2.get('IdeaText'); //text
IdeaList[IdeaListCounter,2] = object2.get('IdeaImage'); //image
IdeaList[IdeaListCounter,3] = object2.get('IdeaLikes'); //likes
IdeaList[IdeaListCounter,4] = object2.get('IdeaReport'); //reports
Your nested query is asynchronous.
Check out the answer at the following for guidance:
Nested queries using javascript in cloud code (Parse.com)

Categories