2

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)
  • 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 :/ –  Jan 28 '15 at 05:43
  • from MDN [Array.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) – Santiago Hernández Jan 28 '15 at 05: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; –  Jan 28 '15 at 05:51
  • thanks for that :), check my answer i think that would help – Santiago Hernández Jan 28 '15 at 05:55

3 Answers3

1

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);
        }
    });
};
Santiago Hernández
  • 5,438
  • 2
  • 26
  • 34
  • this line: `var messages = data["result"];` – Santiago Hernández Jan 28 '15 at 05: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. –  Jan 28 '15 at 05: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 '15 at 06: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! –  Jan 28 '15 at 06:04
  • all right, i think that i understand more your snippet if that array is inside the message variable that the php handler sends then try this: `var messages = data['message']['result'];` – Santiago Hernández Jan 28 '15 at 06:08
  • That was it, so simple and took forever lol. Thank you so much! –  Jan 28 '15 at 06:11
0

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

terary
  • 940
  • 13
  • 30
0

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]);
}
  • 1
    You are just copying answers from http://stackoverflow.com/questions/16626735/how-to-loop-through-an-array-containing-objects-and-access-their-properties without any explanation. –  Jan 28 '15 at 05:46