Query multiple JSON tables inside javascript for loop - javascript

Codepen with working example.
I'm still new to javascript, so I could be going about this the wrong way. If you can suggest a better way for me to do this, I would greatly appreciate it; always love to learn a new, better way!
Here goes:
I use the array iD to generate the URL's of the 10 JSON tables I'm pulling data from.
var set = $('.set');
var iD = [
"od6",
"o9mpc0w",
"ol96q2e",
"olqcdyz",
"ojfsm09",
"oijguh3",
"obmuic4",
"oup920g",
"ohwlz67",
"omk1ruv"
];
function photoSet(){
var idLength = iD.length;
for (var i = 0; i < idLength; i++) {
Once I iterate through the array, I use an ajax call to query each one.
$.ajax({
url:'https://spreadsheets.google.com/feeds/cells/1TBjwQNVRMNzuyZRxr9yX-fUKWw6gpUX69o9PQc79COs/' + iD[i] + '/public/values?alt=json',
async: true,
dataType: 'jsonp',
success: photos});
After they're queried, I retrieve the data from the cells of each JSON table and use it as an image src to insert into the document.
function photos(results){
for(var a = 1; a <= 1; a++) {
var imageEntry = results.feed.entry[a].content.$t;
set.append('<li class="image"><img src="'+ imageEntry +'"/></li>');
console.log(imageEntry);
}
}
}
}
photoSet();
Here's the issue: I need to have the resulting images in the same order as the array iD
Every time the page loads, the images are displayed in a different order. I know it's doing this because the queries are coming in at slightly different times, thus resulting in a different order every page load.
Does it have something to do with storing the ajax calls in variables, then grabbing them one at a time? Do I need another callback? As the nesting gets more complex, I get more confused :/
I've been searching high and low for how to do this, but just can't seem to figure it out. It seems with each new discovery I make, a new problem arises. Such is the nature of code, I suppose. Thank you all for your help :)
Also, I saw this question, but am having trouble figuring out how to apply its answer to my code. If I do, I'll remove this question promptly.

You can add id to the building of the li-
set.append('<li class="image" id="sequnce"><img src="'+ imageEntry +'"/></li>');
e.g
<li class="image" id="1"><img src="d.gif"/></li>
<li class="image" id="4"><img src="d.gif"/></li>
<li class="image" id="3"><img src="d.gif"/></li>
And after you finish to retrieve all the data from the Json you can sort the li.
You can use this link How to sort LI's based on their ID

In our iD for loop we change the ajax to something like this...
var allResults = {}, successCount = 0;
$.ajax({
url: 'https://spreadsheets.google.com/feeds/cells/1TBjwQNVRMNzuyZRxr9yX-fUKWw6gpUX69o9PQc79COs/' + iD[i] + '/public/values?alt=json',
async: true,
dataType: 'jsonp',
success: function( results ) {
successCount++;
allResults[ iD[i] ] = photos( results );
if ( successCount == iD.length ) {
//All data received...
for (var i2 = 0; i2 < idLength; i2++) {
set.append( allResults[ iD[i2] ] )
}
}
}
});
Now instead of calling photos directly we call a anonymous (unnamed) function which keeps a track of successful ajax request count and stores the images HTML in new object allResults with key matching iD array. When success count is equal iD.length we know all requests have been made and al HTML is saved in allResults object. We then run a for loop like we did for ajax requests and populate data in sequence of iD array.
The photos function, doesn't immediately append html into set now but returns all data, it should look like this...
function photos(results){
returnString = '';
for(var a = 1; a <= 1; a++) {
var imageEntry = results.feed.entry[a].content.$t;
returnString += '<li class="image"><img src="'+ imageEntry +'"/></li>';
console.log(imageEntry);
}
return returnString;
}
Hope that helps...

Related

Javascript - Read JSON by dynamic url inside loop

I have to make a call to a json that varies according to the id that I pass in the url, for this I must go through an array of identifiers and modify the url of the json inside the loop. But unfortunately it doesn't go inside the json function until the loop iterations have finished.
var IdList = ['1401', '5724', '5802', '3502', '2101'];
for(l = 0; l < IdList.length; l++){
$.getJSON('https://www.urljson.com?id='+IdList[l]+'', function(emp) {
price = emp.data.price;
currency = emp.data.currency;
});
}
Could someone tell me what is happening?
Thanks!

How to store a Facebook Graph API response as a Javascript Array?

I'm wondering how to store the response from a Facebook API call into a Javascript array.
This is the call I'm making:
FB.api('/MYAPPID/scores/?fields=user', function(response) {
for (var i = 0; i < response.data.length; i++){
var grabbedarray = response.data[i].user.id;
console.log(grabbedarray);
}
})
The call FB.api('/MYAPPID/scores/?fields=user' returns a data set that has "name" and "id" properties for each element in the array, but I'm only interested in storing the "id" parts of the array.
The above code iterates through the response from the call, it checks user.id in each row of the array, and then the console.log shows the id for that row. This means that var grabbedarray is appearing several times in the console, showing a different id each time. I understand why this is happening, but I'm trying to get all the ids stored into one array, and then I'd like to console.log that.
So the final result in the console should be something like:
[456345624, 256456345, 253456435727, 376573835, 2652453245]
I've tried changing the call to FB.api('/MYAPPID/scores/?fields=user.id' in the hope that the response will show only a list of ids, but it's not working.
Does anyone have any idea how to solve this problem?
Thank you in advance!
To keep the approach you were using, you can push each new id you find into an array you define outside of the for loop.
var idArray = [];
FB.api('/MYAPPID/scores/?fields=user', function(response) {
for (var i = 0; i < response.data.length; i++){
idArray.push(response.data[i].user.id);
}
console.log(idArray);
})
You could also use map to transform the response array into what you want.
var idArray = [];
FB.api('/MYAPPID/scores/?fields=user', function(response) {
idArray = response.data.map(function(x){ return x.user.id });
console.log(idArray);
})

Looping Through an Array of Arrays returned by JSON API Call

I am writing an App using Intel XDK, and I am using a Wordpress API to obtain user information. The url produces the following:
{"status":"ok","0":{"id":2,"username":"testshop","shopname":"shopname","url":"","displayname":"testshop","nickname":"Test Shop","avatar":"80","longitude":"54.5591894,-1.237610600000039","gender":"Menswear","mensCats":"Tech Geek| Indie Lad| Vintage Gent| Casual Bloke","womensCats":""},"1":{"id":3,"username":"testShop2","shopname":"","url":"","displayname":"testShop2","nickname":"Test Shop 2","avatar":"","longitude":"54.5576249,-1.2475360999999338","gender":"Womenswear","mensCats":"","womensCats":"Indie Babe| Vintage Queen"}}
I have another API call, which when called, only returns one array, and I can access this information fine, as I do not have to loop through. However, I am not sure how to loop through the above. Below is the code I use to get the JSON:
$.getJSON(url, function(json){
var name = json.nickname;
}
Could anyone help with the best way to iterate through the data.
Thank You
Since your code doesn't produce an array but an object then you can do something like this:
$.getJSON(url, function(json){
if(json.status === "ok")
{
var keys = Object.keys(json).filter(function(str){ return str !== "status" });
for(var i = 0 ; i < keys.length; i++)
{
console.log(json[keys[i]]);
}
}
}
JSFIDDLE.

Parse 2-dimensional array retrieved as string from database

I am building an array of data that is being retrieved from the cells of a table. The resulting array looks something like this:
[["","","",""],["","9/2/14","","9/17/14"],["","","89ol",""],["","687k","","9-0["p/"],["","245g","245g","356h"],["","","",""],["","","4j6","467j"],["","","9/9/14",""]]
I'm saving the data to a MySQL database as a string in one field. I now need to retrieve that data and iterate through it to repopulate the table.
I'm getting the data to an $.ajax function as a string in the above format.
How can I get the individual cell data to populate the cells properly?
UPDATE:
Here's the php code I'm using to retrieve the data:
$queryGetUserTaskNotes = "SELECT userProgressNotes FROM userProgress WHERE userProgressUserID = $userID AND userProgressSiteID = $siteID and userProgressNotesTable = '" . $taskTableID . "'";
$resultGetUserTaskNotes = #mysqli_query($dbc,$queryGetUserTaskNotes);
if ($resultGetUserTaskNotes) {
$taskNotes = mysqli_fetch_assoc($resultGetUserTaskNotes);
echo $taskNotes['userProgressNotes'];
}
Here's how I'm getting the data from the php script
function GetTaskNotes(siteID,tableID) {
$.ajax({
url: 'script.php',
data: {getTaskNotes:'true', userID:userID, siteID:siteID, tableID:tableID},
success: function(data) {
console.log('GetTaskNotes data: ' + data);
}
});
}
As for what I've tried so far, I've been working with how to parse the string on the js side in the success function. JSON.parse(data) didn't work and frankly, I'm not sure what else to try.
Thanks!
Unless you have very special needs in terms of performance/logic, I would say it would be better to use a hash of name/value pairs (a.k.a an object) where the names in the hash correspond to actual fields in the database. That being said, lets say for the sake of argument that the arrays are populated by .push() calls, in which case a simple nested for loop should work:
'use strict';
var array = JSON.parse(string);
var cell, row, i, j;
var table = document.createElement('table');
for (i=0; i < array.length; ++i) {
row = document.createElement('tr');
for (j=0; j < array[i].length; ++j) {
cell = document.createElement('td');
cell.innerHTML = array[i][j];
row.appendChild(cell);
}
table.appendChild(row);
}
document.appendChild(table);
Where string is the string you get back from the DB when its time to repopulate.
I think the steps here for you are going to be:
In PHP, provide a URL that JS can do a GET against that will return the data. The way that is structured and looks will depend somewhat on what framework (if any) that you're using. Be sure to return that data as JSON using a built in PHP JSON encode method.
In JS, do a GET like so:
$.ajax({
url: 'your url here',
type: 'GET',
success: function(data) { console.log(data); }
});
In your success function, I assume you'll handle iterating over your object and inserting it into the DOM. I would look at jQuery's $.each() method for that. When it comes to "populating the cells properly", it'd be helpful to see your HTML and JS in a jsFiddle or something.
Good luck!
References:
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jquery.each/

How can I "Parse" array returned by ajax?

I have 3 spans on my page that contain numbers. On click of a button I would like to retrieve an ajax response, and if the response is valid (it should be an array of 3 elements) I would like to update the numbers in these spans. Could you please recommend a solution via jQuery?
Thank You.
$.getJSON(url, function(resp)
{
var list = resp.list;
if(!list)
{
throw new Exception("list is not set");
}
for(var i = 0; i < list.length; i++)
{
$('#span' + (i + 1)).text(list[i]);
}
});
if the spans have ids span1, span2, and span3. See $.getJSON for more information. Note that you can add error handling by using $.ajax instead.
You can just implement this by usig jQuery.getJson(url,callback(data,textStatus)) .
for example :
$.getJSON(url, function(data,textStatus){
var spanValues = data.list;
$('#span_Id').text(spanValues [i]);
...
});

Categories

Resources