jquery tokeninput read items from database

709 views Asked by At

how can read items of jquery from database with php and ajax? I use this plugin : http://loopj.com/jquery-tokeninput this is my jquery code :

$("#demo-input-local").tokenInput(
'http://exapmle.com/index.php/mantaghe', { 
theme: "facebook",
hintText: "Know of any cool games?",
noResultsText: "Nothin' found.",
searchingText: "Gaming...",
preventDuplicates: true
}   
);

This is my php code in this url http://exapmle.com/index.php/mantaghe :

$db = JFactory :: getdbo();
$sql1 = "select * from sb5qt_djcf_regions where parent_id='0'";
$db ->setquery($sql1);
$result = $db -> loadAssocList();
$str = array( "id" => "value",
"name" => "value",
"mantaghe" => "value");
foreach($result as $res)
{
$str['mantaghe'] = $res['mantaghe'];
$str['id'] = $res['id'];
$str['name']= $res['name']; 
}
echo json_encode($str);
1

There are 1 answers

4
Chris On

You said in the comments your service returned:

{"id":"504","name":"\u0645\u0631\u06a9\u0632\u06cc","mantaghe":"0"}

The service must return a JSON array, rather than a single object. Although looking at your PHP, it looks like you may have got a bit mixed up writing it - you're current code is constantly overwriting the properties of one single object, rather than creating an array of objects.

I haven't written any PHP in years, so the syntax is probably wrong, but you want something more like this.

$arr = array();
foreach($result as $res)
{
$token['mantaghe'] = $res['mantaghe'];
$token['id'] = $res['id'];
$token['name']= $res['name'];
$arr[] = $token;
}
echo json_encode($arr);