Reputation: 4336
Okay, i want to process another javascript request foreach value returned inside a JSON response from a jQuery Request, Here's the current code i'm using for this request
function waitForEvents(){
$.ajax({
type: "GET",
url: "/functions/ajax.php?func=feed&old_msg_id="+old_msg_id,
async: true, /* If set to non-async, browser shows page as "Loading.."*/
cache: false,
timeout:50000, /* Timeout in ms */
success: function(data){
var json = jQuery.parseJSON(data);
**//Foreach json repsonse['msg_id'] call another function**
setTimeout('waitForEvents()',"1000");
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert("Error:" + textStatus + " (" + errorThrown + ")");
setTimeout('waitForEvents()',"15000");
},
});
};
for each json response variable ['msg_id'] i want to call another javascript function but don't know how to process the array using a foreach in javascript, any idea how ?
Upvotes: 1
Views: 5870
Reputation: 34197
use a simple for loop, likely faster than for each
function myfunction(id){
alert("myid:"+id):
}
var i=0;
for (i=0; i< json.length;i++){
var thisId = json[i].msg_id;
myfunction(thisId);
}
simpler:
function myfunction(id){
alert("myid:"+id):
}
var i=0;
for (i=0; i< json.length;i++){
myfunction(json[i].msg_id);
}
since you asked:
function checkArrayElements(element, index, array) {
console.log("a[" + index + "] = " + element);
var myId = element.msg_id;
};
json.forEach(checkArrayElements);
and discussion in case older browsers where not implimented: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach so you can do that
Upvotes: 0
Reputation: 2469
As you're already using jQuery, you can use the $.each function:
http://api.jquery.com/jQuery.each/
$.each(json.msg_id, function (index, value) {
// Do something with value here, e.g.
alert('Value ' + index + ' is ' value);
})
Upvotes: 2