-1

i need to create a object at a php page and send it as a response by a ajax call to use in in the response page as a javascript object.

This kind of object i need to create an pass through.

var areaChartData = {
            labels  : ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
            datasets: [
              {
                label               : 'Electronics',
                fillColor           : 'rgba(210, 214, 222, 1)',
                strokeColor         : 'rgba(210, 214, 222, 1)',
                pointColor          : 'rgba(210, 214, 222, 1)',
                pointStrokeColor    : '#c1c7d1',
                pointHighlightFill  : '#fff',
                pointHighlightStroke: 'rgba(220,220,220,1)',
                data                : [65, 59, 80, 81, 56, 55, 40]
              },
              {
                label               : 'Digital Goods',
                fillColor           : 'rgba(60,141,188,0.9)',
                strokeColor         : 'rgba(60,141,188,0.8)',
                pointColor          : '#3b8bba',
                pointStrokeColor    : 'rgba(60,141,188,1)',
                pointHighlightFill  : '#fff',
                pointHighlightStroke: 'rgba(60,141,188,1)',
                data                : [28, 48, 40, 19, 86, 27, 90]
              }
            ]
          }

How i can do it? Is it possible?

relo80
  • 245
  • 2
  • 13
  • 1
    Sure, it's possible. Create object in PHP and than use `json_encode`. – pavel May 05 '21 at 12:12
  • Related : [How do I pass variables and data from PHP to JavaScript?](https://stackoverflow.com/questions/23740548/how-do-i-pass-variables-and-data-from-php-to-javascript) – charlietfl May 05 '21 at 12:13

1 Answers1

0

Three steps to doing this:

  1. Create the object as a PHP associative array containing a mix of associative arrays and plain arrays.

  2. Send it to the browser as JSON via json_encode.

  3. On the browser, parse the response from JSON (either as part of receiving it — the fetch API will parse JSON for you, as will axios — or parse the text of the response manually via JSON.parse).

For example:

<?php
$example = array(
    "x" => [1, 2, 3],
    "y" => ["a", "b", "c"],
    "z" => array(
        "nested" => 42,
        "stuff" => [4, 5, 6]
    ),
);
echo json_encode($example);

That will output this JSON (formatting added):

{
    "x": [1, 2, 3],
    "y": ["a", "b", "c"],
    "z": {
        "nested": 42,
        "stuff": [4, 5, 6]
    }
}

...which can be parsed into a JavaScript object tree:

const json = `{
    "x": [1, 2, 3],
    "y": ["a", "b", "c"],
    "z": {
        "nested": 42,
        "stuff": [4, 5, 6]
    }
}`;
const obj = JSON.parse(json);
console.log(obj.x[0]); // 1
console.log(obj);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875