1

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?

1
  • 2
    you may have to escape the json encoded value else it will become something like data-pictures="{"picture1":"item1",...}", so as you can see the string literal is terminated before picture1 Commented Jul 15, 2014 at 2:29

3 Answers 3

3

Change this line

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

to

<td data-pictures="<?php echo htmlentities(json_encode($array)); ?>"></td>
Sign up to request clarification or add additional context in comments.

Comments

1

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>

1 Comment

Thank you! Such an easy oversight!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.