Sotero Aranguren
Sotero Aranguren

Reputation: 33

Live search using codeigniter Json Mysql Ajax Jquery

I am doing a project on Live Search Using Jquery Ajax, Php Codeigniter and Mysql
This search is similar to http://w3schools.com/ajax/ajax_aspphp.asp but with MYSql

Here is my database table:

CREATE TABLE IF NOT EXISTS `ix08s_subjects` (
  `SUB_ID` int(11) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(211) DEFAULT NULL,
  `added_by` int(11) DEFAULT NULL,
  `date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`SUB_ID`),
  KEY `FK_ix08s_subjects` (`added_by`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 COMMENT='to store the subjects' AUTO_INCREMENT=3 ;

--

-- Dumping data for table ix08s_subjects

INSERT INTO `ix08s_subjects` (`SUB_ID`, `NAME`, `added_by`, `date_added`) VALUES
(1, 'physics', 2, '2013-05-31 10:07:55'),
(2, 'physics', 2, '2013-05-31 10:41:09');

Here is my model code- Subjectmodel.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Subjectmodel extends CI_Model {
   public function __construct() {
        parent::__construct();
    }
    function getSubject($search){
        $this->db->select("SUB_ID,NAME");
        $whereCondition = array('NAME' =>$search);
        $this->db->where($whereCondition);
        $this->db->from('ix08s_subjects');
        $query = $this->db->get();
        return $query->result();
    }
}
?>

Here is my Controller code- Subject.php

<?php
class Subject extends CI_Controller {
    function __construct() {
        parent::__construct();
        $this->load->model('SubjectModel');
    }
    public function index(){
        $search=  $this->input->post('search');
        $query = $this->SubjectModel->getSubject($search);
        echo json_encode ($query);
        $this->load->view('search', $query);
    }
}
?>

Here is my View code- Search.php

<html>
<head>

<script type="text/javascript" language="javascript" src="http://somexyz/js/javascripts/plugin/jquery.js"></script>
<script type="text/javascript" src="http://somexyz/js/javascripts/plugin/json2.js"></script>
<script>
    $(document).ready(function(){
      $("#search").keyup(function(){
        if($("#search").val().length>3){
        $.ajax({
            type: "post",
            url: "http://localhost/ibps/index.php/subject",
            cache: false,               
            data:'search='+$("#search").val(),
            dataType: 'json',
            success: function(response){
                $('#finalResult').html("");
                var obj = JSON.parse(response);
                if(obj.length>0){
                    try{
                        var items=[];   
                        $.each(obj, function(i,val){                                            
                            items.push($('<li/>').text(val.NAME));
                        }); 
                        $('#finalResult').append.apply($('#finalResult'), items);
                    }catch(e) {     
                        alert('Exception while request..');
                    }       
                }else{
                    $('#finalResult').html($('<li/>').text("No Data Found"));       
                }       

            },
            error: function(){                      
                alert('Error while request..');
            }
        });
        }
        return false;
      });
    });
</script>
</head>
<body>
<div id="container">

<input type="text" name="search" id="search" />
<ul id="finalResult"></ul>
</div>
</body>
</html>

When ever I type four letters into the search box I get this alert pop up

Error while request..

Not getting the values from the database

Upvotes: 0

Views: 4730

Answers (1)

James Birkett
James Birkett

Reputation: 490

The problem is with the returned format of http://localhost/ibps/index.php/subject.

You have added the line:

$this->load->view('search', $query);

When compaired to your previous question 'Live search using Codeigniter Mysql'. This is probably adding an html template to the output and not the json expected by the ajax call.

Have a look at Return JSON with CodeIgniter

Upvotes: 1

Related Questions