I am trying to include an echo from a php file to javascript file.
I have this code in my php-file:
<?php
...I connect and load list from database here...
for($i=0;$i<sizeOf($list_rows);$i++) {
echo '"'.$list_rows[$i]['name'].'": null,';
}
?>
and the following code in my JavaScript file:
<script>
$('input.autocomplete').autocomplete({
data: {
HERE I WANT TO HAVE THE ECHO
},
});
</script>
The php-file is giving me the correct echo when I open it directly, but my javascript file don't. Can you help me?
You can make following changes
<?php
...I connect and load list from database here...
$echo_text = '';
for($i=0;$i<sizeOf($list_rows);$i++) {
$echo_text .= '"'.$list_rows[$i]['name'].'": null,';
}
?>
<script>
$('input.autocomplete').autocomplete({
data: {
'<?php echo $echo_text;?>'
},
});
</script>
In the php code concat strings
PHP CODE
<?php
$string = "";
for($i=0;$i<sizeOf($list_rows);$i++) {
$string.='"'.$list_rows[$i]['name'].'": null,';
}
?>
in javascript just get that php variable like this -
<script>
var res = '<?php echo $string; ?>';
alert(res);
$('input.autocomplete').autocomplete({
data: {
res
},
});
</script>
Try this:
PHP:
<?php
$names = [];
for($i=0;$i<sizeOf($list_rows);$i++) {
if($list_rows[$i]['name'] != ""){
array_push($names, array('label' => $list_rows[$i]['name'], 'value' => $list_rows[$i]['name']));
}
//echo '"'.$list_rows[$i]['name'].'": null,';
}
$names = json_encode($names);
?>
JS:
<script>
$('input.autocomplete').autocomplete({
data: '<?php echo $names; ?>',
});
</script>
Is it correct, that I can put php via into a javascript file?
My first idea was to load the javascript file in html and this javascript loads an external php file :/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.