Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

autocomplete from php array

i wrote this code to do autocomplete from php array but it is not working, can anybody 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
	});
});
like image 730
Sina Nouri Avatar asked Feb 06 '15 21:02

Sina Nouri


1 Answers

if you want to use php array in jQuery you have to user 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>
like image 123
PHP Worm... Avatar answered Oct 01 '22 06:10

PHP Worm...