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)
4
  • 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 :/ Commented Jan 28, 2015 at 5:43
  • from MDN Array.forEach Commented Jan 28, 2015 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; Commented Jan 28, 2015 at 5:51
  • thanks for that :), check my answer i think that would help Commented Jan 28, 2015 at 5:55

3 Answers 3

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

6 Comments

this line: var messages = data["result"];
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.
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);
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!
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'];
|
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

Comments

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 Comment

You are just copying answers from stackoverflow.com/questions/16626735/… without any explanation.

Your Answer

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