user
user

Reputation: 213

Ajax autosearch is not working properly

Jquery:

<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript">

    function ajaxSearch() {
     // alert('hai');
        var input_data = $('#search_data').val();
     // alert(input_data);

        $.ajax({
            type: "POST",
            url: "search/auto_search",
            data1: {search_data:input_data},
            success: function(data1) {
                alert(data1);
                // return success
                if (data1.length > 0) {
                    $('#suggestions').show();
                    $('#autoSuggestionsList').addClass('auto_list');
                    $('#autoSuggestionsList').html(data1);
                }
            }
        });
    }

</script>

View:

<div class="something">
    <input name="search_data" id="search_data" type="text" onkeyup="ajaxSearch();">
     <div id="suggestions">
         <div id="autoSuggestionsList"></div>
     </div>
 </div>

Controller:

public function auto_search() {

    $search_data = $this->input->post('search_data');
  //echo "aaaaaaaaaaaa".$search_data; die();
 // print_r($search_data);  die();
    $query = $this->search_model->autocomplete($search_data);
 // print_r($query);  die();
 // if (!empty($query)) {
        foreach ($query->result() as $row)
            echo $row->uid.'</br>'  ;
            echo  $row->name ;
        }
...

when i alert the data1 in jquery, the result is entire view that is code that is given in view. What is the problem with this code? Can you explain this and provide a solution for this problem? Controller, Model and jquery is given above.

Upvotes: 0

Views: 64

Answers (2)

JOE LEE
JOE LEE

Reputation: 1058

some framework Controller will auto load view file to display, maybe you need to stop it.

or try to add exit();

public function auto_search() {

    //your code
exit();
}

remark : think about ajax retrun json or html,

Upvotes: 0

Vishal Patel
Vishal Patel

Reputation: 1745

if i am not wrong then you are trying for autocomplete box.and as per my experice instead of following code use array to store your data and convert it to json and then send that json to browser then then fill that array to autolist.

  foreach ($query->result() as $row)
  {
       echo $row->uid.'</br>'  ;
        echo  $row->name ;
   }

instead of above code use following code.

  $response = array();
  foreach ($query->result() as $row)
  {
    $response[] = array('uid'=>$row->uid,'name'=>$row->name);
  }
  echo json_encode($response);

I hope it will help you and need any help then commnet it.

Upvotes: 1

Related Questions