Reputation: 755
I have a query result in controller which I encoded to json
. I need to pass it to javascript, because I want to use typeahead js
to autocomplete search input. This is my attempt:
My controller (Admin.php):
public function promotion()
{
$this->db->distinct();
$this->db->select("from_email");
$this->db->from('booking');
$query2 = $this->db->get();
$results = $query2->result_array();
$data['from_email'] = json_encode($results);
$this->template->render('admin/promotion',$data,'admin');
}
My input search (to search based on email address from database):
<input type="text" name="email" class="form-control input-lg typeahead typeahead-from-email" id="email" required="required" autocomplete="off" tabindex="1" />
Javascript :
var emails = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace('from_email');
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: base_url + 'admin/promotion'
});
$('.typeahead-from-email').typeahead({
hint: true,
highlight: true,
minLength: 3
},
{
name: 'from_email',
displayKey: 'from_email',
source: from_email
});
It's not working.
Upvotes: 0
Views: 109
Reputation: 3536
No need to call view or template
public function promotion()
{
$this->db->distinct();
$this->db->select("from_email");
$this->db->from('booking');
$query2 = $this->db->get();
$results = $query2->result_array();
echo json_encode($results); //<-- Just echo the json result
}
Then in your javascript
prefetch: <?php echo base_url('admin/promotion'); ?>
Upvotes: 0
Reputation: 225
try this first to check if your typeahead is actually working then try searching "Ala" or "Cal". I'll update my answer based on your response.
var emails = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California']
});
$('.typeahead-from-email').typeahead({
hint: true,
highlight: true,
minLength: 3
},
{
name: 'from_email',
source: emails
});
Upvotes: 1