puks1978
puks1978

Reputation: 3697

jQuery UI Autocomplete and CodeIgniter

I am trying to implement a simple autocomplete script using jQuery UI and CodeIgniter 2 but my model keeps telling me there is an undefined variable so I dont know if my setup is right.

My view

$(function() {
   $("#txtUserSuburb").autocomplete({
      source: function(request, response){
         $.ajax({ 
            url: "autocomplete/suggestions",
            data: { 
               term: $("#txtUserSuburb").val()
            },
            dataType: "json",
            type: "POST",
            success: function(data){
               response(data);
            }
         });
      },
      minLength: 2
   });
});

My controller

function suggestions(){
   $this->load->model('autocomplete_model');
   $term = $this->input->post('term', TRUE);
   $rows = $this->autocomplete_model->getAutocomplete($term);
   echo json_encode($rows);
}

My Model

function getAutocomplete() {
   $this->db->like('postcode', $term, 'after'); 
   $query = $this->db->get('tbl_postcode');
   $keywords = array();
   foreach($query->result() as $row){
      array_push($keywords, $row->postcode);
   }        
   return $keywords;
}

There arent any errors except it doesn't seem to be passing the $term variable to the model.

Upvotes: 0

Views: 1900

Answers (2)

Kundan Prasad
Kundan Prasad

Reputation: 576

change post value in Ajax

$(function() {
  $("#txtUserSuburb").autocomplete({
      source: function(request, response){
         $.ajax({ 
            url: "autocomplete/suggestions",
            data: { 
               term: request.term //change post value
            },
            dataType: "json",
            type: "POST",
            success: function(data){
               response(data);
            }
         });
      },
      minLength: 2
   });
});

set page header as JSON in a controller

function suggestions(){
   $this->load->model('autocomplete_model');
   $term = $this->input->post('term', TRUE);
   $rows = $this->autocomplete_model->getAutocomplete($term);
   $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode($rows));
}

Upvotes: 0

continuum
continuum

Reputation: 93

Yeah, I think you need getAutocomplete() to have a param "$term":

function getAutocomplete($term) {

Upvotes: 3

Related Questions