how can i get array value from php to javascript, and use the value for other function in javascript? here is my source code:
<?php
$sSql = "SELECT * from contactinfo order by description, nama_cp";
$r1 = $dbconn->execute ($sSql);
$idset=array();
$no=1;
while (($r1) && (!$r1->EOF)) {
$s1 = $r1->GetRowAssoc(false);
$idset[$no]=$s1[id];
$no++;
}
?>
<script type="text/javascript">
function getdata(valarray){
//source..
}
$(document).ready(function() {
var line=<?php echo($no); ?>;
var i;
for(i=1;i<line;i++){
$("#action"+i).click(function() {//button, that named with action+int
//var valarray = ??? -------->value of array idset;
getdata(valarray);//use data array for other function..
});
}
});
</script>
in this code, i want to use valarray in function getdata().
how can i get array value from php to javascript, and use the value for other function in javascript? here is my source code:
<?php
$sSql = "SELECT * from contactinfo order by description, nama_cp";
$r1 = $dbconn->execute ($sSql);
$idset=array();
$no=1;
while (($r1) && (!$r1->EOF)) {
$s1 = $r1->GetRowAssoc(false);
$idset[$no]=$s1[id];
$no++;
}
?>
<script type="text/javascript">
function getdata(valarray){
//source..
}
$(document).ready(function() {
var line=<?php echo($no); ?>;
var i;
for(i=1;i<line;i++){
$("#action"+i).click(function() {//button, that named with action+int
//var valarray = ??? -------->value of array idset;
getdata(valarray);//use data array for other function..
});
}
});
</script>
in this code, i want to use valarray in function getdata().
Share Improve this question asked Nov 4, 2011 at 2:44 irwanirwan 3331 gold badge4 silver badges11 bronze badges3 Answers
Reset to default 4Here is your solution:
var valarray = <?php echo json_encode($idset); ?>;
console.log('we got: '+ valarray)
When you used alert - you can see the results since it's a json and not test. The best for you will be to use Chrome dev tools (or Firebug on FF) and see in the console the results.
You can use json_encode like in the answer to this question: How to convert this PHP array into a JavaScript array?
If you don't know/don't want to use json, then you just need to think about how php works. It is processed by the server before being sent to the browser, therefore if you want anything in php to be available in javascript you have to print it like so:
<?php
$myArr = array();
// add stuff to $myArr
echo '<script type="text/javascript">\n';
echo 'var myJSArr = new Array();\n';
$count = 0;
foreach($myArr as $myItem) {
echo 'myJSArr[' . $count . '] = ' . $myItem . ';\n';
$count += 1;
}
echo '</script>\n'
?>
Keep in mind if you want to send string values from php to the javascript using the above method you need to print the quotes(") around them as well. You can use your browsers view source to check the generated javascript syntax if its not working.
var valarray = <?php echo json_encode($idset); ?>