5

I wrote this code to do autocomplete from a 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>

JS script:

$(function() {
var availableTags = [ <?php echo implode(',', $cars); ?>];
    $( "#cartag" ).autocomplete({
    source: availableTags
    });
});
2
  • tell us what does your JS look like after the PHP is executed. Commented Feb 6, 2015 at 22:04
  • sorry but i am beginner, how can i tell you what does it look like after executing? Commented Feb 6, 2015 at 22:11

3 Answers 3

7

If you want to use a PHP array in jQuery, you have to use 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>
Sign up to request clarification or add additional context in comments.

Comments

1

You need to quote each string in the array (otherwise they'll be treated as variables, which are undefined):

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

3 Comments

are you including jquery ui?
yes i do <script type="text/javascript" src="ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/…>
json strings should not be manually crafted -- this would not be a reliable technique if the values themselves might contain double quotes.
-1

You need jquery ui.
Here is a simplified version, without considering PHP;
jsfiddle

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

to parse your array correctly 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>

2 Comments

i need to put php array into java array automatically, what do you suggest to do with that?
This doesn't say anything about how to pass the array from the php/html to the js code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.