Autofill from php array

I wrote this code to make autocomplete from a php array, but it does not work, can anyone help?

php array

$cars = array("Volvo", "BMW", "Toyota"); 

my form

 <form id="frm" method="post"> <input id="cartag" type="text" name="car"> </form> 

script

 $(function() { var availableTags = [ <?php echo implode(',',$cars); ?>]; $( "#cartag" ).autocomplete({ source: availableTags }); }); 
+5
source share
3 answers

if you want to use php array in jQuery you have to json_encode .

like this:

 var availableTags = <?php echo json_encode($cars); ?>; 

Working demo:

 <?php $cars = array("Volvo", "BMW", "Toyota"); ?> <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <form id="frm" method="post"> <input id="cartag" type="text" name="car"> </form> <script> $(function() { var availableTags = <?php echo json_encode($cars); ?>; $( "#cartag" ).autocomplete({ source: availableTags }); }); </script> 
+5
source

You need to quote each row in the array (otherwise they will be treated as undefined variables):

 var availableTags = [ <?php echo '"' . implode('","', $cars) . '"'; ?> ]; 
+1
source

You need jquery ui.
Here is a simplified version, excluding PHP.
jsfiddle

 var lst = ["Volvo", "BMW", "Toyota"]; $( "#cartag" ).autocomplete({ source: lst }); 

to correctly parse your array from PHP to js:

 <script type='text/javascript'> <?php $php_array = array('abc','def','ghi'); $js_array = json_encode($php_array); echo "var javascript_array = ". $js_array . ";\n"; ?> </script> 
0
source

Source: https://habr.com/ru/post/1212843/


All Articles