Svetoslav
Svetoslav

Reputation: 4686

Jquery array returns after post

Hi I am doing one checkscript with jquery and php I have written this :

$.post("chatController.php", {
    ssha:"<?php echo $sechs1;?>", 
    user: "<?php echo $_SESSION["username"];?>", 
    class:1
 }, function(data){ 
    $.each(data, alert(this));
 }, "json");

And from the PHP file I get something like :

echo json_encode(array("John","2pm"));

This array can have 0,1,2....unlimitied entries.. How I alert each of this entrie one by one ?

Perhaps something like:

For each data > alert(this)

Upvotes: 0

Views: 218

Answers (3)

Headshota
Headshota

Reputation: 21449

to have proper json you must have key value pairs in your php array, something like:

json_encode(array("name"=>"John","time"=>"2pm"));

to list all object properties you can do:

for(var prop in data){
  if(data.hasOwnProperty(prop)){  // this prevents inherited properties
    console.log(prop);
  }
}

Upvotes: 1

Christopher
Christopher

Reputation: 704

Perhaps you are searching for JQuery.each().

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816600

You are calling alert immediately and passing its return value to $.each. You have to pass a function reference instead:

$.each(data, function(index, item){
    alert(item);
});

Be careful with using class as property name. It is a reserved keyword and you could have problems with it in browsers. Either put it in a string:

'class': 1

or rename it.

Upvotes: 3

Related Questions