views:

294

answers:

3

Hello,

I am still searching for an answer but I haven't come up with a solution yet

My question: How can I parse the json array

I send it like this

$data= mysql_fetch_array($r);
header('Content-type: application/json');

?>     
{
    "check": "<?php echo $check?>",
    "productcode": "<?php echo $code?>",
     "values": [<?php echo $data?>]
}
<?php

on the ajax side I do this on the single values wich works fine

success: function(data,textStatus){
    //return values
    identification=data.check;

if I want to acces the array I do something like this and I get undefined

value=data.values[1];

What am I doing wrong

thanks, Richard

A: 
$data= mysql_fetch_array($r, MYSQL_NUM);

could correct the problem.

It would be helpful to get the json you get in the ajax part

RC
what is it know then, an asociative?is associative bad for parsing?
Richard
according to the doc, it's both associative and num
RC
+1  A: 

You need to encode your array as JSON, too:

{
    "check": "<?php echo $check?>",
    "productcode": "<?php echo $code?>",
     "values": [<?php echo json_encode($data); ?>]
}

The easiest way is probably to put everything in a PHP array and serialize this as JSON:

$output = array(
    "check" => $check,
    "productcode" => $code,
    "values" => $data
);

echo json_encode($output);

Then you can be sure that it is being encoded properly.

Daff
thanks, could you comment on the mysql_NUM, can I still get the values by name then, in ajax success function.
Richard
You could use mysql_fetch_assoc which returns an associative array. That means, that you then can access the columns in a row by its name in JavaScript (and not by its index). Just check the result and then you'll see what it does.
Daff
With msql_fetch_array, associative is the default, because I get my results by name, or both I get from @RC, s comment below.
Richard
Oh ok sorry. Well the manual said that MYSQL_NUM gives you a non associative array.
Daff
+1  A: 

Try this:

$data= mysql_fetch_array($r);
header('Content-type: application/json');

$json = array(
    'check' => $check,
    'productcode' => $code,
    'values' => $data
    );

print json_encode($json);

It's more tidy than printing the json manually. json_encode turns a PHP array into a json string.

Rowan