How can i do form validation in codeigniter if i don't want to refresh the page? Basically i do this:
$config = array(
array(
'field' => 'c_name',
'label' => 'Name',
'rules' => 'trim|required'
),
array(
'field' => 'c_job',
'label' => 'Job',
'rules' => 'trim|required',
)
);
$this->form_validation->set_rules($config);
if($this->form_validation->run() == true)
{
$this->load->model('model');
//.....
}
else{
$this->load->view('view');
}
But if i send data with ajax and the page doesn't refresh, How can i do form validation?
Edit:
Thanks @ Amra Kojon. That's good and works but the new problem is this:
if ($this->form_validation->run() == FALSE) {
echo validation_errors();
}
else {
//echo 'hi';
$value = $this->input->post('value');
$values = array(
'c_name' => $value['c_name'],
'c_job'=> $value['c_job'],
'c_address'=> $value['c_address'],
'c_phone'=> $value['c_phone'],
'c_mail'=> $value['c_mail'],
'c_state'=> $value['c_state'],
'c_intrest'=> $value['c_intrest'],
'c_added_info'=> $value['c_added_info']
);
$add = $this->customers_model->add_customer($values);
echo $add;
}
If i just say echo "something" in the else part, It works and if the validation were OK, It echo hi but if i write theme in database (Which the value array has data and in not ajax way, it insert date), It doesn't work and the else part isn't working!!!
If you gave your JS- jquery Ajax code it would more efficient to understand your problem.. Don't worry! Try my following instruction...
Get get form value and pass to form as
$(document).ready(function(){ var dataString = $("#FormId").serialize(); var url="ControllerName/MethodName" $.ajax({ type:"POST", url:""+url, data:dataString, success:function (data) { alert(data); } }); })Controller :
Load library form_validation in construct as ...
$this->load->library('form_validation');
$this->load->helper('form');
Now write your controller as ...
function MethodName {
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('fname','First Name', 'required');
$this->form_validation->set_rules('lname','Last Name', 'required');
$this->form_validation->set_rules('email','Email Address','required|valid_email|is_unique[sec_users.email]');
if ($this->form_validation->run() == FALSE) {
echo validation_errors();
}
else {
// To who are you wanting with input value such to insert as
$data['frist_name']=$this->input->post('fname');
$data['last_name']=$this->input->post('lname');
$data['user_name']=$this->input->post('email');
// Then pass $data to Modal to insert bla bla!!
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With