Help with ajax autocomplete by querying the database
The question what comes in my mind is whether my query is returning the values from the database or did I miss anything in my code. I have been trying to figure it out but I am unable to understand.
print_r($tagnames) doesn't print anything on the screen.
This code is part of the controller
function get_Names() {
// Convert the string to the lowercase
$q = strtolower($this->input->post('q', TRUE));
if(!$q) {
return;
}
$tagnames[] = $this->autocomplete_model->getData();
print_r($tagnames);
echo json_encode($tagnames);
}
I have autocomplete_model.php and this code is part of the model
class Autocomplete_model extends CI_Model {
public function __construct() {
parent::__construct();
}
function getData() {
$q = $this->db->query("SELECT * FROM tags");
if($q->num_rows() > 0) {
foreach($q->result() as $row) {
$data[] = $row->tag_name;
}
return $data;
}
}
}
I have the following code in my view
$(document).ready(function() {
$(function() {
$( "#tagname" ).autocomplete({
source: function(request, response) {
$.ajax({ url: "<?php echo site_url('generator/get_Names'); ?>",
data: { term: $("#tagname").val()},
开发者_运维问答 dataType: "json",
type: "POST",
success: function(data){
response(data);
}
});
},
minLength: 2
});
});
});
Thanks in advance.
It looks like your AJAX call is sending "term" as post data but your get_Names() method is looking for a post parameter of "q". Change one of them and I think you should be good.
精彩评论