user875139
user875139

Reputation: 1621

PHP array to javascript returning one character

I have the following PHP array:

 $array = array("picture1"=>"item1", "picture2"=>"item2",
     "picture3"=>"item3", "picture4"=>"item4");

I am trying to get the array values through this html code using jquery's .attr() method.

<td data-pictures="<?php echo json_encode($array); ?>"></td>

pictures = $(this).attr('data-pictures');

When I do a console log for the pictures variable, I am getting only a "{" and nothing more. Can someone help?

Upvotes: 1

Views: 80

Answers (3)

user1978142
user1978142

Reputation: 7948

As @Arun has said, quotes must be escaped first or the attribute will be terminated. You can use htmlspecialchars() in this case. Consider this example:

<?php $array = array("picture1"=>"item1", "picture2"=>"item2", "picture3"=>"item3", "picture4"=>"item4"); ?>
<table>
    <tr>
        <td data-pictures="<?php echo htmlspecialchars(json_encode($array)); ?>"></td>
    </tr>
</table>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){

    var pictures = $.parseJSON($('td').attr('data-pictures'));
    console.log(pictures);

});
</script>

Upvotes: 1

Gerardo G&#243;mez
Gerardo G&#243;mez

Reputation: 127

Change this line

<td data-pictures="<?php echo json_encode($array); ?>"></td>

to

<td data-pictures="<?php echo htmlentities(json_encode($array)); ?>"></td>

Upvotes: 3

Mijoe
Mijoe

Reputation: 256

This is because of mistake in using quotes. You can use :

<td data-pictures='<?php echo json_encode($array); ?>'></td>

Note Change double quote with single quote

Upvotes: 0

Related Questions