1

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.

2
  • 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. Commented Aug 27, 2018 at 7:21
  • A simple approach would be convert PHP array to JSON and then use JSON.parse to access elements. Commented Aug 27, 2018 at 7:21

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Im getting unexpected identifier in console even though its showing this var opDestino = "{"imagen":"Logo_RGB.jpg","alt":"test123","destino":"op_list_gen"}";
Remove the double quotes and try again, please. (I will update the answer)
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); ?>;

2 Comments

Im getting unexpected identifier in console even though its showing this var opDestino = "{"imagen":"Logo_RGB.jpg","alt":"test123","destino":"op_list_gen"}";
Yes remove the quotes. js expects a valid json string. The quotes on the outside of the json encoded output violated the json formatting.
1

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.