salman salman - 3 months ago 22
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

controller



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'),
);
$this->load->model('suppliermodel');
if($this->suppliermodel->checkData($user['Name'])){
if ($this->session->userdata('user_id'))
$detail = 'Already exist';
$this->load->view('admin/includes/header');
$this->load->view('admin/includes/sidemenu');
$this->load->view('admin/add_supplier',['exist'=>$detail]);
$this->load->view('admin/includes/footer');
$this->load->view('admin/includes/add_supplier_footer');

}
else{
$this->suppliermodel->add($user);
}

}


model



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


what is ajax code and controller function

Answer

How about this?

Controller

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[suppliers.name]');
    //$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);
}

JavaScript

$.ajax({
    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 {

            alert('success!');
        }
    }
});

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.