I have a multidimensional array, here:
$noticeDate = json_encode( $noticesDates );
and I want to pass the array into javascript:
var unavailableDates[] = $noticeDate;
Both variables are in the same php file so there is little point using $.getJSON, which basically looks for the variable in an external file. However, how do I pass the object into the javascript array in the same script.
Cheers
asked Mar 29, 2012 at 12:27
bobo2000
1,8777 gold badges34 silver badges54 bronze badges
3 Answers 3
You cant directly assign php variables to js, but you can use something like that:
<script>
var unavailableDates = jQuery.parseJSON('<?php echo json_encode($noticeDates) ?>');
</script>
Sign up to request clarification or add additional context in comments.
3 Comments
R2-Bacca
@Christoph's solution lacks the client-side JSON parsing that is included here. This is the more complete solution.
bobo2000
var unavailableDates = jQuery.parseJSON('<?php echo json_encode($noticesDates) ?>'); document.write(unavailableDates); doesnt seem to print it out
erdeszt
Why do you want to print it out? It's an object you can't just simply print it. If that's your goal you should use a different format imho.
use this
var array = JSON.parse("<?php echo json_encode($noticesDates) ?>");
Comments
Try this one: $.pareseJSON()
here is example:
var json = "<?php echo json_encode($noticesDates); ?>";
jsArray = jQuery.parseJSON(json);
answered Mar 29, 2012 at 12:32
ShirazITCo
1,0416 gold badges24 silver badges39 bronze badges
1 Comment
hitautodestruct
How does this even attempt to answer the question? Please change your answer to something more resembling one.
default