0

The array below could return in various ways (with more or less elements):

array(4) { ["imagen"]=> string(11) "bánner.jpg" ["alt"]=> string(5) "muaka" ["destino"]=> string(7) "op_tipo" ["tipo"]=> string(13) "obj_connected" }

array(3) { ["imagen"]=> string(12) "Logo_RGB.jpg" ["alt"]=> string(7) "test123" ["destino"]=> string(11) "op_list_gen" }

Im saving this in a variable in PHP called: $filtrosBanner;. How can I get the values from this in jQuery?

I have saved the variable in jQuery as follows:

var opDestino = "<?php echo $filtrosBanner; ?>";

This returns an array but im not sure how to access each value individually.

Victor York
  • 1,621
  • 4
  • 20
  • 55
  • 2
    jQuery uses Javascript syntax. If you want an PHP object to be read as a Javascript object, you have to encode it to a format accepted by it. Using `json_encode()` you could do that. – Rafael Aug 27 '18 at 07:21
  • A simple approach would be convert PHP array to JSON and then use JSON.parse to access elements. – Nakul Aug 27 '18 at 07:21

4 Answers4

1

I would use json_encode(). This should create a json object for your var opDestino.

Like so:

var opDestino = <?php echo json_encode($filtrosBanner); ?>;
Joseph_J
  • 3,654
  • 2
  • 13
  • 22
  • Im getting unexpected identifier in console even though its showing this `var opDestino = "{"imagen":"Logo_RGB.jpg","alt":"test123","destino":"op_list_gen"}";` – Victor York Aug 27 '18 at 07:27
  • Yes remove the quotes. js expects a valid json string. The quotes on the outside of the json encoded output violated the json formatting. – Joseph_J Aug 27 '18 at 07:29
1

The most simple approach for your task would be:

var opDestino = <?php echo json_encode($filtrosBanner); ?>;

This way you are converting an object (or array) from PHP to Javascript syntax.

Rafael
  • 1,495
  • 1
  • 14
  • 25
  • Im getting unexpected identifier in console even though its showing this `var opDestino = "{"imagen":"Logo_RGB.jpg","alt":"test123","destino":"op_list_gen"}";` – Victor York Aug 27 '18 at 07:27
  • Remove the double quotes and try again, please. (I will update the answer) – Rafael Aug 27 '18 at 07:28
0

You need to implode your array as string using your PHP code and save it in a php variable as

PHP

$myarray=implode(',',$array);

Now take it in a variable in your script and then explode it using , to get your final array as

JQUERY

var myarray='<?php echo $myarray;?>';

var originalarray=myarray.split(',');

Note: but it will work for only indexed array, not associative array

RAUSHAN KUMAR
  • 5,846
  • 4
  • 34
  • 70
0

Return the array with json_encode in PHP.

return json_encode($filtrosBanner);

In Javascript/jQuery use

var obj = JSON.parse(<?php echo $filtrosBanner?>);

To use this object , use it like this.

obj.propertyname
Muhammad Osama
  • 985
  • 8
  • 17