tags:

views:

31

answers:

4

Hey guys I have an ajax jquery function that receives data from a php script. I want to return an array with all the online users which is retrieved from a mysql statement, and I want to send other separate variables I need for other purposes along with it. If anyone has any ideas, I would greatly appreciate it. NOTE: the example below is to illustrate what I want to do, I understand that json-encoding the array with other variables is dysfunctional.

JQUERY

$.ajax({
type: "POST",
   data: "parameters",
   url: "retrieval.php",
    dataType: 'json',
   success: function(json)
   {
    $('#div1').html(json.array);
    $('#div2').html(json.variable1);
$('#div3').html(json.variable2);
}
})

PHP

$qryuserscount1="SELECT * FROM active_users";
$userscount1=mysql_query($qryuserscount1);
while ($row = mysql_fetch_array($userscount1)) {
$onlineuser= $row['username'];
$id=$row['id'];

$data[]=$onlineuser.$id; //for example there are 3 users, should send 3 entries back
}
$data['variable1']='something';
$data['variable2']='something else';

$out = json_encode($data);
print $out;
A: 

You really want to send back a JSON object containing what you need.

{
    "Users" : [
        "Jim",
        "Bob",
        "Sue"
    ],
    "Something" : 2,
    "Else" : "This is something else."
}
ChaosPandion
A: 

You could use the following structure:

{loggedUsers: [the list], variable1: 'something', variable2: 'something else'}
zneak
+1  A: 

On PHP side you should have something along the lines of:

$result = array();

$qryuserscount1="SELECT * FROM active_users";
$userscount1=mysql_query($qryuserscount1);
while ($row = mysql_fetch_array($userscount1)) {
  $onlineuser= $row['username'];
  $id=$row['id'];

  $result['array'][]=array('name'=>$onlineuser, 'id' => $id); //for example there are 3 users, should send 3 entries back
}
$result['variable1']='something';
$result['variable2']='something else';

$out = json_encode($result);
print $out;

JQuery side can remain as it is.

Kamil Szot
Thanks Kamil, I tried your approach however the jquery side does not seem to recognize the array. As soon as I convert the data['array'] to your format, the function dies. I tried testing the page and it seems to return the proper information, but jquery is not having it. This is the json array it returned {"variable1":"test","variable2":"testing","array":[{"entry":"user1"},{"entry":"user2"},{"entry":"user3"}]}
Scarface
nvm I used $.each(json.array, function (i, elem) { $('#users_online').append(elem.entry);});
Scarface
A: 

In your PHP, the variable data should be an array (in PHP an array is actually an ordered map).
data['ids'] would be an array of ids.
data['variable1'] would be variable1 etc.

then json_encode(data) would give you the json you need.

Ofri Raviv