I am new to jQuery and hope someone can help me with this.
I have an Ajax call with the success function (data) returning an array like the below.
Now I have to loop through this and for each "tID" I have to do something with the corresponding "content".
I was thinking of using something like the following but couldn't figure out how to apply this here:
$.ajax({
type: "post",
url: "ajax.php",
cache: "false",
data: {
node: 'fetchContent',
tIDs: tIDs
},
success: function(data){
$.each(data.arr, function(index, value){
console.log(value.content);
});
}
});
Can someone help me with this ?
Example array (Ajax result):
array(3) {
[0]=>
array(2) {
["tID"]=>
int(1)
["content"]=>
string(6) "Value1"
}
[1]=>
array(2) {
["tID"]=>
int(2)
["content"]=>
string(6) "Value2"
}
[2]=>
array(2) {
["tID"]=>
int(3)
["content"]=>
string(6) "Value3"
}
}
Many thanks in advance.
3 Answers 3
You can use nested for loop for the same:
var i,j,arrayItem;
for (i = 0; i < outerArray.length; ++i) {
arrayItem = outerArray[i];
for (j = 0; j < arrayItem.length; ++j) {
console.log(arrayItem[j].tID);
console.log(arrayItem[j].content);
}
}
Edit(after discussing with OP):
There is no need for 2-D array, 1D array is more suited, so the array becomes:
var data= [
{
"tID" : 1,
"content": "Value1"
},
{
"tID" : 2,
"content": "Value2"
},
{
"tID" : 3,
"content": "Value3"
}
];
And the for loop becomes:
for(i=0;i<data.length;i++){
console.log(data[i].tID);
console.log(data[i].content);
}
See the fiddle : "http://jsfiddle.net/Lvkbtuwz/1/"
9 Comments
In php you have to return not array but json_encode($array)
then you can use the array as Object in JS.
-----Edit---21.07.2015 if array in PHP looks like this
echo json_encode(array(0 => array("name" => "Gen"), 1 => array("name" => "Peter")));
**Notice the sequential array indexes 0,1*
then the json will look like this, can be used as array each element as object
[{"name":"Gen"},{"name":"Peter"}] //and then can you iterate using
$.each(arrayFromPhp, function (index, obj)
{
console.log(obj.name); //will output gen and Peter
});
But if you array in PHP looks like this
echo json_encode(array(3 => array("name" => "Gen"), 8 => array("name" => "Peter")));
**Notice the array indexes are not sequential 3,8*
Then the JSON looks likes this are not array any more
{"3":{"name":"Gen"},"8":{"name":"Peter"}}
Then you have to iterate like this
for (i in arrayFromPhp)
{
console.log(arrayFromPhp[i].name) //will output gen and peter
}
2 Comments
The basic idea of iterating through arrays can be achieved using javascript.
arrays have forEach function where your could iterate through the array elements. Use the following example to build your solution.
Asuming you get a JSON response.
var response = JSON.parse(ajaxRespons);
response.forEach(function(element,index){
element.forEach(function(innerElement,index){
//access ur inner elements here
})
})
The above is just an idea. You would have to do some trial runs to get the idea.
.ajax.phpreturn your data?