Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am currently using Ajax to repeatedly pull console logs from an application using its API. When doing a var_dump() of the return values in PHP, it is an array of objects which I will need to loop through and pull the values.

This is of course simple in PHP but as inexperienced with Javascript as I am, I cannot figure this out with for or foreach loops. I have used console.log with Developer Console and the contents are there but any help on how to loop through this would be appreciated.

JS/Ajax:

function getConsoleMessages()
{
    var messageBox = document.getElementById("console_message");

    // Clear the message box contents
    //messageBox.value = '';

    $.ajax({
        type: "POST",
        url: "ajax.php",
        data: { 'action': 'getConsoleMessages' },
        dataType: 'json',
        success: function(data)
        {
            var messages = data['message'];

            messages.forEach( function (item)
            {
                var x = item.Contents;
                console.log(x);
            });
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        { 
            alert("Status: " + textStatus); alert("Error: " + errorThrown); alert("Message: " + XMLHttpRequest.responseText);
        }
    });
};

PHP Handler:

case "sendConsoleMessage":
{
    $message = $_POST["message"];

    if (empty($message))
    {
        $response['status'] = "failed";
        $response['message'] = "Command parameter was not received.";
    }
    else
    {
        $amp->sendConsoleMessage($message);

        $response['status'] = "success";
        $response['message'] = $message;
    }

    echo json_encode($response);

    break;
}

PHP var_dump:

object(stdClass)[2]
  public 'result' => 
    array (size=40)
      0 => 
        object(stdClass)[3]
          public 'Timestamp' => string '/Date(1422419818830-0500)/' (length=26)
          public 'Source' => string 'Console' (length=7)
          public 'Type' => string 'Console' (length=7)
          public 'Contents' => string 'Assigned anonymous gameserver Steam ID [A:1:721403909:5132].' (length=60)
      1 => 
        object(stdClass)[4]
          public 'Timestamp' => string '/Date(1422419819038-0500)/' (length=26)
          public 'Source' => string 'Console' (length=7)
          public 'Type' => string 'Console' (length=7)
          public 'Contents' => string 'VAC secure mode is activated.' (length=29)
      2 => 
        object(stdClass)[5]
          public 'Timestamp' => string '/Date(1422419819145-0500)/' (length=26)
          public 'Source' => string 'Console' (length=7)
          public 'Type' => string 'Console' (length=7)
          public 'Contents' => string 'tf_server_identity_account_id not set; not logging into registered account' (length=74)
share|improve this question
    
I used console.log to print out the returned value to developer console and added it to the original message, however it seems to have lost formatting :/ –  Brett Powell Jan 28 at 5:43
    
from MDN Array.forEach –  Santiago Hernández Jan 28 at 5:44
    
I just updated the original post with my function and used the array forEach() but I am just getting "undefined is not a function" on var x = item.Contents; –  Brett Powell Jan 28 at 5:51
    
thanks for that :), check my answer i think that would help –  Santiago Hernández Jan 28 at 5:55

3 Answers 3

up vote 1 down vote accepted

try this:

function getConsoleMessages()
{
    var messageBox = document.getElementById("console_message");

    // Clear the message box contents
    //messageBox.value = '';

    $.ajax({
        type: "POST",
        url: "ajax.php",
        data: { 'action': 'getConsoleMessages' },
        dataType: 'json',
        success: function(data)
        {
            var messages = data['message']['result'];

            messages.forEach( function (item)
            {
                var x = item.Contents;
                console.log(x);
            });
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        { 
            alert("Status: " + textStatus); alert("Error: " + errorThrown); alert("Message: " + XMLHttpRequest.responseText);
        }
    });
};
share|improve this answer
    
What was changed? –  Brett Powell Jan 28 at 5:55
    
this line: var messages = data["result"]; –  Santiago Hernández Jan 28 at 5:56
    
I tried it but didn't work, "result" isn't anything. I just updated my OP to show my php code that sends the response, you can see "message" is where I am placing the result contents. –  Brett Powell Jan 28 at 5:58
    
sorry about that, but if that is the php handler which sends the ajax response then you are sending the message inside an object, you sould be able to receive it with this: var message = data["message"]; console.log(message); –  Santiago Hernández Jan 28 at 6:02
    
How do I actually loop over each value though? I would like to manually log each "Source" and "Contents" value myself, which is what the issue is. Thanks for the help thus far! –  Brett Powell Jan 28 at 6:04

From looking at your data, I think you want to do the standard

for(i;i<count;i++)
{

   //then and this is the part I believe you are missing:
    for (variable in object) 
    {  str += variable + ":" + object[variable] ;  }

}

see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

share|improve this answer

Syntax:

for ([start]; [condition]; [final-expression])
    statement

Rules:

Traditional way of iterating over arrays.
Can use var, but scope is always the complete surrounding function.

Example:

var arr = [ "a", "b", "c" ];
for(var i=0; i < arr.length; i++) {
    console.log(arr[i]);
}
share|improve this answer
1  
You are just copying answers from stackoverflow.com/questions/16626735/… without any explanation. –  Brett Powell Jan 28 at 5:46

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.