I'm using jquery-autocomplete plugin to lookup into an array from suggestions/autocomplete.
ref: https://github.com/devbridge/jQuery-Autocomplete
PHP (1)
$stmt = $dbh->query("SELECT tag_name FROM tags");
$tags = array();
$tags = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
echo json_encode($tags);
/*
var_dump($tags);
"array(6) {
[0]=>
string(1) "tag1"
[1]=>
string(2) "tag2"
[2]=>
string(3) "tag3"
[3]=>
string(4) "tag4"
}
"
*/
PHP (2)
echo ('["tag1","tag2","tag3","tag4"]');
PHP (3)
$a = ["tag1","tag2","tag3","tag4"];
echo json_encode($a);
JavaScript
$.ajaxSetup({ cache: false, async: false });
var myTags = [];
$.get( '/action.php', {action: 'get_tags'}).done( function(data){
console.log(data);
myTags = eval(data);
//myTags = JSON.parse(data);
});
$('#tagInput').autocomplete({
lookup: myTags
});
Both PHP v1 and PHP v2 will provide a proper array console.log(data)
.
However, the array coming from PHP v1 json_encode($tags)
won't work with the plugin (it simply doesn't recognize the array). While PHP v2 array echo ('["tag1","tag2","tag3","tag4"]');
works just fine. PHP v3 also won't work.
What is wrong in this code? Why json_encode()
array isn't being recognized?