This question already has an answer here:
I have a php array that I want to pass as a parameter to a javascript function onClick. The function, however, is in another file. I try to explain.
File map.php:
<head>
<script type="text/javascript" src="../public/js/map.js"></script>
<script type='text/javascript'>
var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];
//alert(js_array[0]); //this alert works
</script>
</head>
//code...
<form method="post" enctype="multipart/form-data" action="">
<input type="submit" name="submit" value="Post" onClick="createMap(js_array); return false;"/>
</form>
File map.js. I tried to print the array via an alert but does nothing:
for(i=0; i<js_array.length; i++) {
alert(js_array[i]);
}
function createMap(js_array) {
//code...
}
What's wrong? Thank you very much
EDIT Thanks for the replies but still does not work. I modified the code like this:
File map.php:
<head>
<script type='text/javascript'>
var js_array = JSON.parse(<?php echo "json_encode($addresses)"; ?>);
//alert(js_array[0]); //this alert works
</script>
<script type="text/javascript" src="../public/js/map.js"></script>
</head>
//code...
<form method="post" enctype="multipart/form-data" action="">
<input type="submit" name="submit" value="Post" onClick="createMap(js_array); return false;"/>
</form>
File map.js:
for(i = 0; i < js_array.length; i++) {
alert(js_array[i]);
}
function createMap(js_array) {
//...
}
json_encode($addresses)
. That's a legit PHP function call, not something you want to just echo out. – citizenslave Jan 16 '14 at 22:04var js_array = <?php echo json_encode($addresses); ?>;
. If that doesn't work, you would need to check what js errors are being reported. It might not even be this. – Jonathan Kuhn Jan 16 '14 at 22:07