0

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

4
  • what is it? return $query->result(); return false; Commented Sep 5, 2016 at 12:26
  • this if($this->suppliermodel->checkData($user['Name'])){ should be if(count($this->suppliermodel->checkData($user['Name'])) > 0){ Commented Sep 5, 2016 at 12:27
  • you are passing arg in the function checkData in controller but not in modal Commented Sep 5, 2016 at 12:30
  • this is working but i want it through ajax Commented Sep 5, 2016 at 12:50

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

i want it through ajax
@salman I've updated the answer contains the code that you want. If fails, the controller returns a set of JSON containing status and errors message. Then you can handle it in JavaScript code. I use this as my solution.
The main idea of the answer is that you don't have to make a function again your own by use set_rules method provided by Codeigniter. If form validation fails, return an encoded error message as JSON so that you can handle yourself, anyway you want.
@salman: just review this: stackoverflow.com/questions/23172903/ajax-json-unexpected-token ... chk this, or enjoy kro dost

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.