Skip to content Skip to sidebar Skip to footer

Autocomplete From Php Array

i wrote this code to do autocomplete from php array but it is not working, can anybody help? php array my form script

Solution 1:

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

like this:

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

Working demo:

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

?><linkhref="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"><scriptsrc="http://code.jquery.com/jquery-1.10.2.js"></script><scriptsrc="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script><formid="frm"method="post"><inputid="cartag"type="text"name="car"></form><script>

$(function() {
var availableTags =  <?phpecho json_encode($cars); ?>;
    $( "#cartag" ).autocomplete({
    source: availableTags
    });
});

</script>

Solution 2:

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

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

Solution 3:

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:

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

Post a Comment for "Autocomplete From Php Array"