Richard
Richard

Reputation: 4546

parse json array which contains sql array

My question: How can I parse a 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 which works fine

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

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

value=data.values[1];

What am I doing wrong?

Upvotes: 1

Views: 1206

Answers (3)

Rowan
Rowan

Reputation: 5727

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.

Upvotes: 1

Daff
Daff

Reputation: 44215

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.

Upvotes: 1

user180100
user180100

Reputation:

$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

Upvotes: 0

Related Questions