ajaxcodeigniterjquery

chain ajax requests in codeigniter


I have a form that uses autocomplete, I can retrieve the data on the input field but I can't figure out how to get the description data. what I would like to do is get the value from the user then call another controller to get the additional information using ajax (that way I can get more information if needed). Thanks

View

<script type="text/javascript">
$(document).ready(function() {
$(function() {
    $( "#autocomplete" ).autocomplete({
        source: function(request, response) {
            $.ajax({ url: "<?php echo site_url('test/suggestions'); ?>",
            data: { term: $("#autocomplete").val()},
            dataType: "json",
            type: "POST",
            success: function(data){
                response(data);
            }
        });
    },
    minLength: 2

    });
});
});
</script>

<label for="title">Job Title</label>
<input name="title" type="text" id="autocomplete" />

<label for="description">Description</label>
<p id="description" /></p>

Controller

 function suggestions()
{
    $this->load->model('tp_model');
    $term = $this->input->post('term',TRUE);

    if (strlen($term) < 1) break;

    $rows = $this->tp_model->GetAutocomplete(array('keyword' => $term));

    $title_array = array();
    $description_array = array();


    foreach ($rows as $row){
         array_push($title_array, $row->title); 
         array_push($description_array, $row->description);

}
    echo json_encode($title_array);     

}

Model

  function GetAutocomplete($options = array())
{

    $this->db->select('*');
    $this->db->from('test');
    $this->db->like('title', $options['keyword'], 'after');
    $query = $this->db->get();
    return $query->result();

}

Solution

  • You can fetch the description from your controller using "select" event for autocomplete.

    $("input#autocomplete").autocomplete({
        source: ...,
        .....,
        select: function(event, ui) {
            var id = ui.item.id;
            $.ajax({
                url: description_fetch_url, //another controller
                data: "description_id="+id,
                ....
                success: function(data) {
                    $("#description").html(data)
                } 
            });
        }
    });