How to write an index loop for a json object - javascript

I have an image updater. I am loading by JSON the exact same file/partial that show my images.
I would like to write a loop that runs through an index and replaces every image with its equal.
This is the first div in my json object :
[{
"photo": {
"position":1,
"photo_file_size":45465,
"created_at":"2010-10-05T09:51:13-04:00",
"updated_at":"2010-10-05T09:52:29-04:00",
"photo_file_name":"tumblr_l0x861Yc5M1qbxc42o1_400.jpg",
"is_cropped":true,
"crop_h":null,
"photo_content_type":"image/jpeg",
"id":216,
"caption":null,
"crop_w":null,
"photo_uploaded_at":null,
"crop_x":null,
"processing":false,
"gallery_id":26,
"crop_y":null
}
},
...
The next div in that json object would be something like gallery_photos_attributes_1_id .
Update
This is what I got so far.. but the load() method doesn't work correctly. I get a "ONLY GET REQUESTS ALLOWED"
$.getJSON(url, function(data) {
for (var i = 0; i < data.length; i ++) {
url2 = "/organizations/" + 1 + "/media/galleries/" + 26 + "/edit_photo_captions"
var image = $("#gallery_photos_attributes_" + i + "_caption");
url_str = image.siblings("img").attr("src").substr(0, str.lastIndexOf("/"));
image.siblings("img").load(url2, image.siblings("img"));
};
})

Although I'm not 100% I got you right, try this piece of code.
var url = "/organizations/" + organization + "/media/galleries/" + gallery + "/update_photo_index"
$.getJSON(url, function(data) {
// the outer is an array, so just loop as usual
for (var i = 0; i < data.length; i++) {
// fetch something for the current photo
var caption = $("#gallery_photos_attributes_"+ data[i].photo.id +"_caption");
// update source
caption.siblings("img").attr("src","/path/to/images/"+data[i].photo.photo_file_name+"?c="+parseInt(Math.random()*10000));
// update caption
caption.html(data[i].photo.caption);
// and so on...
}
});
Remember that in JSON "[ ... ]" describes an array whereas "{ ... }" describes an object. With an array you can just loop as with every other javascript array. If you got an object, it's like any other javascript object whose fields are accessible either with object.field or object['field']. So using JSON in javascript is nearly a no-brainer.
Hope that helps.

Related

Object array gets overwritten by the last object

I have this array of objects being loaded:
$(document).ready(function () {
$("<div></div>").load("/Stats/Contents #stats", function () {
statcount = $(".list-group-item", this).length;
for (var j = 0; j < statcount; j++) {
statList.push(stat);
}
for (var i = 0; i < statcount; i++) {
statList[i].statId = document.getElementById("statId-" + (i + 1) + "").value;
statList[i].productDescription = document.getElementById("productType-" + (i + 1) + "").value;
statList[i].lastMeasuredInventoryAmount = document.getElementById("statLastMeasureAmount-" + (i + 1) + "").value;
}
)}
)}
.... and so on
Then I get the changed values and save them, however, in the ajax post call, all of the array objects are same (the last one assigned), looks like they get overwritten.
Any ideas? I saw these deferred/promise type code but not sure if there's simpler way.
Thanks.
It sounds like you take the statList array and then push that up to the server, with any respective change. Rather than building and maintaining a list like this, have you thought of switching it around and just grabbing the results out of the markup and building up the array at save point?
$("btnSave").on("click", function(e) {
var data = [];
$(".list-group-item").each(function() {
data.push({
statId: $(this).find(".statid").val(),
.
.
})
});
You wouldn't need to give every element an ID (but could) as my sample uses CSS classes to find the element within the current list item. Additionally, if these are inputs, you could serialize them from the root element more efficiently...

Is it possible to use a string to reference a json object within an Ajax statement?

So i have a javascript function. It performs one ajax call, to retrieve a json object full of data. Within the success function of that ajax call i perfrom ANOTHER ajax call to retrieve the names of the columns of data for that particular set. (yes i'm sure there's a better way but thats not my issue). At this point in time i have two variables: items(json array) and interfaceCols(just an array of strings). Then i try to create an html string to create a table with said data.
Here is my code which will make everything more clear:
$.ajax({
url:"/ryan/nonEmber/ajax.php?table=Interfaces",
beforeSend: function(XMLHttpRequest){},
success: function(data, textStatus) {
interfaceCols = data.split(" ");
$.getJSON("/ryan/nonEmber/getJson.php?table=Interfaces", function( data ){
var items = [];
$.each(data.post, function(key, val){
items.push(val);
});
for(i = 0; i < items.length; i++){
var myString = '<tr id = "visibleRow">';
console.log(items[i].interfaceCols[4]);
for(j = 0; j < interfaceCols.length; j++){
myString = myString + '<td id = "visibleDef">' + items[i].interfaceCols[j] +'</td>';
}
myString = myString + '</tr>';
interfaces.push(myString);
}
});
}
});
My javascript file throws an error on the "myString = myString + '<td id ='... line.
I am almost positive that it is because i'm just placing a string at the end of "items[i]" with ".interfaceCols[j]"
Can anybody suggest a way to do this? The whole point is so that i dont have to manually type out every column name, because i have alot of tables and each table has many columns.
Given a JS object s:
s = {a: 1, b: 2}
You have (at least) two options to access an attribute:
s.a // returns 1
Which seems to be what you are trying to do right now. To access it with a dynamic name, you can use:
s['a'] // returns 1
In your case, it should be:
items[i][interfaceCols[4]]

How to return all objects in javascript array

I have a variable that is created by Flowplayer and available via javascript. If I write the variable to the page directly it just returns 'object Object' so I am assuming this is an array. If I don't know the names of any of the objects inside the array, how can I parse out the data inside?
I know I am missing something really fundamental here, but I don't think I have ever had to get data from an array not knowing what it contains.
Notes:
What I am trying to do is get the onCuePoint caption data embedded
into an RTMP video stream
.valueOf() returns the same thing
Here is the code I am using that returns 'object Object':
streamCallbacks: ['onFI'],
clip:
{
live:true,
provider: 'rtmp',
autoPlay: true,
url:'test1',
onFI:function(clip, info)
{
document.getElementById("onFI").innerHTML += "Data: " + info;
}
}
Thank you
If what you are asking is how you iterate over the contents of an array, you can do so in plain javascript like this:
var arr = [1,2,3];
for (var i = 0; i < arr.length; i++) {
// arr[i] is each item of the array
console.log(arr[i]);
}
Just because something is of type Object does not necessarily mean that it's an array. It could also just be a plain object with various properties on it. If you look at the info argument in either the debugger or with console.log(info), you should be able to see what it is.
You need to iterate through your array and get the results one by one, replace your onFI function with this :
onFI:function(clip, info)
{
var data = "";
// For each value in the array
for (var i = 0; i < info.length; i++)
{
// Add it to the data string (each record will be separated by a space)
data += info[i] + ' ';
}
document.getElementById("onFI").innerHTML += "Data: " + data;
}

issue with array indexing

So I'll jump right to it...
I am a test automation engineer, and I am making a "keyword driven" testing system that is powered with JSON, which tie in with Selenium tests to run on a web browser.
The "keywords" are stored as XML files, and I have a JavaScript function which loads these keywords into an array, and also stores the Index of that keyword. to paf.keywordIndex
Example
$.get("getSteps.php", function(keywords) {
paf.keywords = eval(keywords); // stores into an array...
paf.keywordIndex = -1;
for ( var i = 0 ; i < paf.keywords.length ; i++ ) {
// for each path...
/* alert(paf.keywords[i]); */
$.ajax({url: "./_keywords/" + paf.keywords[i], success: function(xml) {
paf.xml = xml;
paf.keywordIndex++;
var title = $(xml).find("keyword").attr("title");
//var name = $(xml).find("keyword").attr("name");
paf.buffer += ("<option value=\"./_keywords/"+paf.keywords[paf.keywordIndex]+"\">"+title+"</option>");
},
async: false
//cache: false
});
}
$(stepSelectionLocator).html(paf.buffer);
});
getSteps.php is a php service that returns all the xml keywords in a json array. e.g.
["Login.xml","EndSession.xml", "SelectResult.xml", etc...]
Now this function works, but the only problem is, it's not sorted in ANY way. So the output would be -
Login (Login.xml)
Select a result (SelectResult.xml)
End a session (EndSession.xml)
To solve this issue, I added an extra attribute to my <keyword> so now it's <keyword area="basic"> to indicate that this is a basic step. and now my function is -
$.get("getSteps.php", function(keywords) {
paf.keywords = eval(keywords); // stores into an array...
paf.keywordIndex = -1;
for ( var i = 0 ; i < paf.keywords.length ; i++ ) {
// for each path...
/* alert(paf.keywords[i]); */
$.ajax({url: "./_keywords/" + paf.keywords[i], success: function(xml) {
paf.xml = xml;
paf.keywordIndex++;
var title = $(xml).find("keyword").attr("title");
var area = $(xml).find("keyword").attr("area");
//var name = $(xml).find("keyword").attr("name");
paf.buffer.push(area.toUpperCase() + ": " + title);
},
async: false
//cache: false
});
}
paf.buffer.sort(); // array is sorted...
paf.buffer2 = "";
paf.keywordIndex = -1;
for ( var a in paf.buffer ) {
paf.keywordIndex++;
paf.buffer2 += "<option value=\"./_keywords/"+paf.keywords[paf.keywordIndex]+"\">"+ paf.buffer[a] + "</option>";
}
$(stepSelectionLocator).html(paf.buffer2.toString().replace(",", ""));
});
Now the output is
BASIC: End the session (Login.xml)
BASIC: Login (SelectResult.xml)
RESULTS: Select a result (EndSession.xml)
So I've already determined that the index is the issue. However, I cannot figure out a way to fix this..
I am open to alternatives, so if you find a simpler way to index this, please let me know!
First of all, it'd be nice to know exactly the data you get from your initial request.
$.get("getSteps.php", function (keywords) {
paf.keywords = JSON.parse(keywords); // eval is bad! Use JSON.parse instead.
console.log(paf.keywords); // what does it output in the console?
...
Secondly, you can refer to the current index by using just the i variable. If you don't use paf.keywordIndex elsewhere, you can remove it because it's redundant.
Thirdly, are you absolutely, definitely, 100% sure that your ajax requests are *S*ynchronous? If they are not - the responses will arrive at random and the whole thing will require a different approach.
Finally, if you want to apply sorting to your keywords after you got them all, I would recommend pushing them into the buffer array as objects:
buffer.push({
keyword: keywordName, // this is the keyword name
keywordIndex: i, // this is the initial index
keywordArea: areaObtainedFromXML // this is the area you get from xml
});
By using the above approach you will be able to sort your buffer in many ways while retaining the initial order.
Please take a look at a contrived example at this jsfiddle.

Storing and retrieving objects in javascript array();

Hi I've searched for the answer but since the tutorials online are all friends = ("bob","fred","joe"); I dont get anywhere. I would like to be able to store several objects with 1-3 values in each index of the array like:
map = [{ground:0},{ground:0, wall:1},{ground:0, item:3}]
The object I have right now looks like:
node = {};
node = {ground:0, object:1};
But when I try the array way I can't access it, all I get "object Object". What would be the correct way to get the values from the map array one by one?
Do you mean:
var map = [{ground:0},{ground:0, wall:1},{ground:0, item:3}];
for(var i = 0; i < map.length; i++) {
console.log(map[i].ground + " item " + map[i].item);
}
Not sure what you want, or what you mean by "the array way", but if you want to get all the values for say ground, then:
var map = [{ground:0},{ground:0, wall:1},{ground:0, item:3}]
for (var i=0, iLen=map.length; i<iLen; i++) {
alert(map[i].ground);
}
Edit
...
alert('item ' + i + ' : ' + map[i].ground); // item 0 : 0
...

Categories