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 have this PHP Array:

Array
(
    [messages] => Array
        (
            [0] => Array
                (
                    [sender] => 17
                    [receiver] => 4
                    [message] => TEST 2
                    [timestamp] => 1367200891
                    [read] => 0
                )

            [1] => Array
                (
                    [sender] => 17
                    [receiver] => 4
                    [message] => TEST 1
                    [timestamp] => 1367197661
                    [read] => 0
                )

        )

    [new_messages] => 2
)

It gets retrieved via an Ajax Request, using json_encode() to output it in PHP.

function getMessages(rec){
var nmsg = $.ajax({
        type: "GET",
        async: true,
        url: "/ps/getUserMessages.php",
        data: {'u':rec,'s00':s00,'n01':n01,'t02':t02}       
    });
    nmsg.done(function(data) {
        var json = JSON.parse(data);
        if (typeof json.messages[0].message !== 'undefined') {
            printMessage(json);
        }
    }); 
}

And as printMessage() function, for example, i need to do something like:

loop(){
    $("#elem").append(
          '<div>Sender: '+arrayOfValues.sender+'</div>'
         +'<div>Message: '+arrayOfValues.message+'</div>'
    );
}

for each Array of values.

I tried jQuery $.each() and also for() with some examples i found, but i cannot get to work.

share|improve this question
1  
Use serialize() and unserialize() to pass an array between php and js and back again easily. Or you can use json_encode() on your code behind php page. then pass it back to your ajax function which can then dump that into a text box which can be posted and json decoded or you can json decode in javascript too and get an array out either way will work fine. –  Dave Apr 30 '13 at 7:20
    
@Dave I think the problem is not within the encoding, but with accessing the received result. –  Sirko Apr 30 '13 at 7:24
    
Not seeing where the outputting to PHP is in that then as it looks from his code like he's purely attempting to handle it in JS. –  Dave Apr 30 '13 at 7:26
    
@dave i said that i was using json_encode() to pass it to javascript. Read well :) The array it's there just for let you see the structure. –  WiS3 Apr 30 '13 at 7:41
    
if your php is passing it back as JSON then just set your ajax data type to ajax dataType: 'json' and then use the onsuccess function success: function(data){ and you can reference your array as just data["column"] etc so you don't have to mess around parsing json etc you can just directly loop it out. you can remove at least 7 lines of code from your overall code. –  Dave Apr 30 '13 at 7:50

2 Answers 2

up vote 0 down vote accepted

Something like this should work:

function printMessage(data) {
  for( var i=0; i<data.messages.length; i++ ) {
    $("#elem").append(
        '<div>Sender: ' + data.messages[i].sender + '</div>'
       +'<div>Message: ' + data.messages[i].message+ '</div>'
    );
  }
}
share|improve this answer

If you want to iterate over given structure you should use use following as a printMessage:

function printMessage( json ){
    for ( var i in json.messages ) {
        var currentMessage = json.messages[i];

        $("#elem").append(
          '<div>Sender: '+currentMessage.sender+'</div>'
         +'<div>Message: '+currentMessage.message+'</div>'
        );
    }

}
share|improve this answer
4  
Don't use for(var i in ...) for arrays. It's for objects and nothing else. –  Andreas Apr 30 '13 at 7:23
    
So this answer is a suitable solution for this case (reference: w3schools.com/js/js_loop_for.asp) –  Chen Asraf Apr 30 '13 at 7:29
    
@henasraf Better use MDN as a reference instead of w3schools. Why? Have a look at w3fools.com - developer.mozilla.org/en-US/docs/JavaScript/Reference/… –  Andreas Apr 30 '13 at 7:33
    
@Andreas my apologies, I'll correct my ways from now on :) –  Chen Asraf Apr 30 '13 at 7:37

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.