jquery-pluginsjquery-tokeninput

jquery tokeninput : how to pass a dynamic array for autocompletion


With tokenInput, my autocompletion returns nothing and I don't find why.

First I do a query on the database to find all the contacts for the connected user.

I get an array like for instance :

$contacts = Array( [0] => Array ( [id] => 1 [name] => John ) [1] => Array ( [id] => 3 [name] => Peter ) )

Then I use http_build_query as I want to pass the array through URL :

$contacts_url =http_build_query($contacts);

which returns :

print_r($contacts_url)= 0%5Bid%5D=1&0%5Bname%5D=John&1%5Bid%5D=3&1%5Bname%5D=Peter

Then I use tokenInputs, and I send my array through the url :

$(document).ready(function () {
    $("#my-text-input").tokenInput("<?php echo $this->webroot.'populate.php?'.$contacts_url ?>", {theme: "facebook"});
});

the populate.php page contains :

<?php
    header('Content-type: text/javascript');
    $a= $_GET;
    $json_string = json_encode($a);
    echo $json_string;
?>

If I open the php page ../populate.php?0%5Bid%5D=1&0%5Bname%5D=John&1%5Bid%5D=3&1%5Bname%5D=Peter i see:

[{"id":"1","name":"John"},{"id":"3","name":"Peter"}]

which I think looks good

But the autocompletion returns nothing :(

Any help much much appreciated !

Many thanks


Solution

  • By default, the search parameter is also sent as a $GET variable, which I imagine would be messing up your JSON encode.

    A much better way of doing this would be locally, as below:

    $(document).ready(function () {
        $("#my-text-input").tokenInput("<?php echo json_encode($contacts) ?>", {theme: "facebook"});
    });