0

So my website has received some data in the form of a PHP associative array (see below) and I'm trying to convert it to something I can interact with using JavaScript.

enter image description here

JavaScript seems to treat it as just a string and I've had problems using JSON.parse. I have control over the format of this data before it arrives at my JS do I need to restructure it??

Extra Info: Web page A requests data from web page B then web page B collects the data from a database and returns a big array. The array above is the response from web page B in web page A. Each index (["tag"],["current_ids"] etc) actually have large array contained in them, I just shortened it to 1 for ease of understanding.

Taki
  • 17,320
  • 4
  • 26
  • 47
  • 2
    You should encode the array to JSON in PHP! – csabinho Oct 03 '19 at 21:25
  • 1
    You should also show your code ... if you want any hope of having any practical help. People are guessing that you are not using `json_encode`, but frankly it is just a WAG. – YvesLeBorg Oct 03 '19 at 21:37

1 Answers1

0

Data on the web is always sent and received as strings. JavaScript needs the data in a format that it can understand, for example JSON.

PHP has an in-built function to convert your data, e.g. your array, into JSON called json_encode(). It also has a sister function for decoding JSON into PHP called json_decode().

Depending on your setup, you'll want JavaScript to make a XHR request to an endpoint where you're running PHP and then you'll use PHP to process that request and return a JSON string.

Alternatively, you could use PHP to directly echo the JSON string into JavaScript, for example:

<script> <?php echo "var myData = ${json};"; ?> </script>

XHR is the better practice in general but you should use whichever approach best suits your needs.

Optimae
  • 942
  • 1
  • 12
  • 23