Reputation: 1621
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
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
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
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