1

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 ?

1

2 Answers 2

2

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);
})
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

I make the assumption that msg_id is in each element at the root level.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.