Home > database >  PHP output not sliceable by Javascript
PHP output not sliceable by Javascript

Time:09-16

I am using the following array in Javascript and it works perfectly when I use the slice command to access variables

dataSequence = [
    {
        name: 'Week 1',
        data: [1, 2, 2, 1, 1, 2, 2,5]
    }, {
        name: 'Week 2',
        data: [6, 12, 2, 3, 3, 2, 2,6]
    }
    ];

Then when I use this PHP script via Ajax to show the same data.

$out = "[
    {
        name: 'Week 1',
        data: [1, 2, 2, 1, 1, 2, 2,5]
    }, {
        name: 'Week 2',
        data: [6, 12, 2, 3, 3, 2, 2,6]
    }
    ]";
 echo $out;

here is my Ajax call

$.ajax({
url: "gettimedata1.php",
type: 'POST',
}).done(function(msg) {
dataSequence = msg;
data = dataSequence[0].data.slice();
});

It throws the message "Cannot read property 'slice' of undefined".

What do I need to do to format the PHP output correctly ?

Thanks

CodePudding user response:

I believe this is the correct way to output json from PHP

$a = array(
        array('name' => 'week1', 'data' => [1, 2, 2, 1, 1, 2, 2, 5]),
        array('name' => 'week2', 'data' => [6, 12, 2, 3, 3, 2, 2, 6])
);
$json = json_encode($a);
header('Content-Type: application/json');
echo $json;

You should then be able to:

$.ajax({
  url: "gettimedata1.php",
  type: 'POST'
}).done(function(response) {
  data = response[0].data.slice();
});

You may have to fiddle with the PHP a little I do not have a PHP environment to test on and its been a few years since I last coded in it.

  • Related