salman salman - 4 months ago 28
jQuery Question

Data check in database if already exist in codeigniter through ajax

I want to check data in database through ajax in codeigniter how can get check name already exist through ajax


public function insert(){
$user = array('Name' => $this->input->post('name'),
'Cnic' => $this->input->post('cnic'),
'Phone' => $this->input->post('phone'),
'Address' => $this->input->post('address'),
if ($this->session->userdata('user_id'))
$detail = 'Already exist';




public function checkData()
$name = $this->input->post('name');
$this->db->where('Name', $name);
$query = $this->db->get();
if($query->num_rows() >0){
return $query->result();
return $query->result();
return false;

what is ajax code and controller function


How about this?


public function insert(){

    // set a rule that make the Name field is unique by 'set_rules'
    $this->form_validation->set_rules('Name', 'Name Field', 'required|is_unique[]');
    //$this->form_validation->set_rules('[Other Field]', '[Field Name to Display]', '[Restriction]');

    // if the field cannot pass the rule
    if ($this->form_validation->run() === FALSE) {

        $errors = array();

        foreach ($this->input->post() as $key => $value) {
            // Add the error message for this field
            $errors[$key] = strip_tags(form_error($key));
        // Clear the empty fields (correct)
        $response['errors'] = array_filter($errors); 
        $response['status'] = false;

    else {
        // otherwise, call the model
        $result = $this->suppliermodel->add($user);  

        if ( $result ) {
            $response['status'] = true;


    echo json_encode($response);


    url: '//localhost/insert',
    data: {
        Name: $('input[name=Name]').val(),
        Cnic: $('input[name=Cnic]').val(),
        Phone: $('input[name=Phone]').val(),
        Address: $('input[name=Address]').val()
    dataType: 'JSON',
    type: 'POST',
    error: function(xhr) {
        alert('request failed!');
    success: function(response) {

        var response = $.parseJSON(JSON.stringify(response));

        if (response.status != true) {

            $.each(response.errors, function(field, i) {
                alert( field+ ' errors with ' + i)
        else {


Use is_unique[table.fieldToCompare] to make the field is always unique.

Wish it helps.

set_rules restrictions, see the Codeigniter User Guide Form validation

If fails, the controller would return a set of JSON, with field and error message. Then you can handle it in $.ajax's success.