0

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?

1

4 Answers 4

1

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

0

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>

More Info: https://jqueryui.com/autocomplete/#categories

Comments

0

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 :/

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.