Do form validation with jquery ajax in codeigniter - ajax

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!!
}
}

I know your question is a year old but you can use this for the latest bootstrap with codeigniter
<?php
class Yourcontroller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
}
public function index() {
$this->load->view('template/register');
}
public function validate() {
$json = array();
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[password]');
$this->form_validation->set_rules('code', 'Login Code', 'required|numeric|min_length[4]||max_length[8]');
$this->form_validation->set_message('required', 'You missed the input {field}!');
if (!$this->form_validation->run()) {
$json = array(
'username' => form_error('username', '<p class="mt-3 text-danger">', '</p>'),
'email' => form_error('email', '<p class="mt-3 text-danger">', '</p>'),
'password' => form_error('password', '<p class="mt-3 text-danger">', '</p>'),
'confirm_password' => form_error('confirm_password', '<p class="mt-3 text-danger">', '</p>'),
'code' => form_error('code', '<p class="mt-3 text-danger">', '</p>')
);
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($json));
}
}
Ajax Script
<script type="text/javascript">
$( document ).ready(function() {
$('#error').html(" ");
$('#form-submit-button').on('click', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('yourcontroller/validate');?>",
data: $("#form").serialize(),
dataType: "json",
success: function(data){
$.each(data, function(key, value) {
$('#input-' + key).addClass('is-invalid');
$('#input-' + key).parents('.form-group').find('#error').html(value);
});
}
});
});
$('#form input').on('keyup', function () {
$(this).removeClass('is-invalid').addClass('is-valid');
$(this).parents('.form-group').find('#error').html(" ");
});
});
</script>
Full View Code
<div class="container">
<div class="row">
<div class="col-sm-6 ml-auto mr-auto m-auto">
<div class="card mt-5">
<h5 class="card-header"></h5>
<div class="card-body">
<?php echo form_open('agent/register', array('id' => 'form', 'role' => 'form'));?>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<?php echo form_input('username', '', array('class' => 'form-control', 'placeholder' => 'Enter Agent Username', 'id' => 'input-username'));?>
<div id="error"></div>
</div>
<hr/>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<?php echo form_input('email', '', array('class' => 'form-control', 'placeholder' => 'Enter Agent Email', 'id' => 'input-email'));?>
<div id="error"></div>
</div>
<hr/>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<?php echo form_password('password', '', array('class' => 'form-control', 'placeholder' => 'Enter Password', 'id' => 'input-password'));?>
<div id="error"></div>
</div>
<hr/>
</div>
<div class="col-sm-6">
<div class="form-group">
<?php echo form_password('confirm_password', '', array('class' => 'form-control', 'placeholder' => 'Enter Confirm Password', 'id' => 'input-confirm_password'));?>
<div id="error"></div>
</div>
<hr/>
</div>
</div>
<hr/>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<button type="button" class="btn btn-block btn-dark" id="form-submit-button">Register Agent</button>
</div>
</div>
</div>
<?php echo form_close();?>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$( document ).ready(function() {
$('#error').html(" ");
$('#form-submit-button').on('click', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('yourcontroller/validate');?>",
data: $("#form").serialize(),
dataType: "json",
success: function(data){
$.each(data, function(key, value) {
$('#input-' + key).addClass('is-invalid');
$('#input-' + key).parents('.form-group').find('#error').html(value);
});
}
});
});
$('#agent-register-form input').on('keyup', function () {
$(this).removeClass('is-invalid').addClass('is-valid');
$(this).parents('.form-group').find('#error').html(" ");
});
});
</script>

If you are aware about passing data with ajax, then the work flow is as follows.
1) Send form data through ajax to your controller.
2) Do form validation as of now.
3) If success then "echo" value 1
4) If failure, echo value 0
So that using the value in echo, you can determine whether the validation fails or not. I can give you an example if you need
Sample ajax code
$('#form').on('submit', function(e){
e.preventDefault();
var data = $(this).serialize();
$.ajax({
url: 'your url',
type: 'POST',
data: data,
success: function(data){
if(data == 1){
$('#form')[0].reset();
alret('success');
}
else if(data == 0){
alret('failed');
}
},
error: function(){
alert('error');
}
});
});

Create MY_Form_validation in libraries folder
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
private $json = array();
private $opts = array();
function get_json($extra_array = array(),$error_array=array())
{
if(count($extra_array)) {
foreach($extra_array as $addition_key=>$addition_value) {
$this->json[$addition_key] = $addition_value;
}
}
$this->json['options'] = $this->opts;
if(!empty($error_array)){
foreach($error_array AS $key => $row)
$error[] = array('field' => $key, 'error' => $row);
}
foreach($this->_error_array AS $key => $row)
$error[] = array('field' => $key, 'error' => $row);
if(isset($error)) {
$this->json['status'] = 'error';
$this->json['errorfields'] = $error;
} else {
$this->json['status'] = 'success';
}
return json_encode($this->json);
}
}
Call this function in controller if validation failed:
echo $this->form_validation->get_json();
You get the response with form fieldname and errormessage
Example:
{"options":[],"status":"error","errorfields":[{"field":"email","error":"The Mobile Number\/Email\/Username field is required."},{"field":"password","error":"The Password field is required."}]}

Try this is my working (Codeigniter 3.0) basic example to achieve what you want do
include filename.js in your view
document.getElementById("yourForm").reset();
$(document).ready( function() {
var yourForm = $('#yourForm');
yourForm.submit( function(event) {
event.preventDefault();
$.ajax( {
type: 'POST',
url: yourForm.attr( 'action' ),
data: yourForm.serialize(),
success: function(data) {
if (data.code == '200') {
$('#message').html(data.message);
document.getElementById("yourForm").reset();
}
},
error: function(data) {
var response = data.responseText;
var obj = jQuery.parseJSON(response);
if (obj.code == '500') {
var i;
for (i = 0; i < obj.field.length; i++) {
name = obj.field[i];
$('.label-'+name).addClass('label-error');
errors = JSON.stringify(obj.validation);
validate = jQuery.parseJSON(errors);
$('.helper-'+name).html(validate[name]);
}
}
}
} );
} );
} );
view HTML form example
In this example in am using className you can use id as well change filename.js file accordingly
<form id="yourForm" action="base_url/controller/function_name" action="POST">
// Important text after className "label-" & "helper-" must be input name
<label class="label-firstName">Name</label>
<input type="text" name="firstName" />
<span class="helper-firstName"></span>
</form>
<div id="message"></div>
controller PHP code
public function function_name()
{
if(!empty($_POST)) {
$this->load->library('form_validation');
$this->form_validation->set_rules('firstName','First Name','required|max_length[16]');
if($this->form_validation->run())
{
$params = array(
'firstName' => $this->input->post('firstName'),
);
// Model returning $data['newRecord'] with $params and insertId
$data['newRecord'] = $this->Record_model->newRecord($params);
$reply = array();
$reply['code'] = 200;
$reply['record'] = array(
'insertId' => $data['newRecord']['insertId'],
'firstName' => $data['newRecord']['firstName']
);
$reply['message'] = 'Hello, ' .$data['newRecord']['firstName']. ' - We have received your message. ' .$data['newRecord']['insertId']. ' is your reference ID, for this communication.';
header('Content-Type: application/json; charset=UTF-8');
print json_encode($reply);
}
else {
$validation = $this->form_validation->error_array();
$field = array();
foreach($validation as $key => $value) {
array_push($field,$key);
}
$reply = array(
'code' => 500,
'field' => $field,
'validation' => $validation,
'message' => 'Submission failed due to validation error.'
);
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Problem', true, 500);
header('Content-Type: application/json; charset=UTF-8');
print json_encode($reply);
}
}
else {
$reply = array();
$reply['code'] = 403;
$reply['message'] = 'No Direct Access Allowed.';
header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden', true, 403);
header('Content-Type: application/json; charset=UTF-8');
print json_encode($reply);
}
}

If using ajax,...you can't use form_validation library
So you can validate on client side using jquery ...and on server side should use if statement to check submitted data

Related

ajax is not able to call the function of codeigniter

This is Welcome controller method
public function send_otp()
{
echo 'in';
die;
$phone = $_POST['mobile'];
if ($phone != '') {
$mobile_detail = $this->welcome_model->check_if_already_mobile_no($phone);
if (!empty($mobile_detail)) {
if ($mobile_detail['is_verified'] == 'yes') {
$message = 'Already Verified.';
echo json_encode(array('status' => 'error', 'message' => $message));
exit;
} else {
$this->welcome_model->delete_mobile_no($phone);
}
}
$otp = self::generateRandomNo();
$this->welcome_model->insert_mobile_detail($phone, $otp);
$link = file_get_contents("http://49.50.67.32/smsapi/httpapi.jsp?username=aplusv&password=aplusv1&from=APLUSV&to=$phone&text=$otp&coding=0");
$status = '';
if ($link != '') {
$status = 'success';
$message = 'Successfully Otp send to your no.';
} else {
$status = 'error';
$message = 'Error in sending OTP.';
}
echo json_encode(array('status' => $status, 'message' => $message));
exit;
}
}
This is model
public function check_if_already_mobile_no($mobile_no = null)
{
$query = $this->db->get_where('mobile_sms', array('mobile_no' => $mobile_no));
return $query->row_array();
}
public function get_mobile_details($mobile_no = null, $otp = null)
{
$query = $this->db->get_where('mobile_sms', array('mobile_no' => $mobile_no, 'otp' => $otp));
return $query->row_array();
}
public function insert_mobile_detail($phone, $otp)
{
$this->mobile_no = $phone;
$this->otp = $otp;
$this->is_verified = 'no';
$this->created_at = date('Y-m-d H:i:s');
$this->db->insert('mobile_sms', $this);
}
This is view
<div class="container" style="margin-top: 25px;">
<div class="row">
<div class="col-md-12" id="response_msg"></div>
<div class="col-md-4" id="enter_mobile">
<form method="POST" action="#">
<div class="form-group">
<label for="phone">Phone </label>
<input type="text" class="form-control" id="mobile" name="phone" placeholder="Enter Mobile">
</div>
<button type="button" name="send_mobile" id="send_otp" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="assets/js/jquery.js"></script>
<script type="text/javascript">
// var base_url = "<?php echo base_url();?>";
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>
$(function () { // start of doc ready.
$("#send_otp").on('click', function (e) {
var mobile = $('#mobile').val();
alert(mobile);
$.ajax({
url: '<?php echo site_url('index.php/welcome/send_otp'); ?>',
data: {'mobile': mobile},
type: "post",
dataType: 'json',
success: function (data) {
if (data.status == 'success') {
$('#response_msg').html('<div class="alert alert-success" role="alert">' + data.message + '</div>');
$('#mobile_no').val(mobile);
$('#enter_mobile').hide();
$('#verify_otp_form').show();
} else {
$('#response_msg').html('<div class="alert alert-danger" role="alert">' + data.message + '</div>');
}
}
});
});
in ajax is not getting call ie $.ajax is not working here and my controller ie welcome with method send_otp is not called here.
why my function in controller is not getting called
how to solve the issue
what is the proper way to call the controller function using base_url
i have check the console also it is not showing any error
I noticed that you are using site_url() slightly incorrectly: don't write index.php there, just use site_url('welcome/send_otp')
Don't forget you have an unconditional die() at the top of your send_otp method - it will prevent any code below itself from executing

How to get Advanced Custom Fields values with Ajax in Wordpress

I'm trying to do a WP_query on a custom-post-type but for some reason I cannot get the values from the custom-field-types of these posts.
Here is what I got so far (functions.php)
function fetch_cases(){
$args = array(
'post_type' => array('case'),
'post_status' => array('publish'),
'posts_per_page' => 5
);
$query = new WP_Query($args);
if($query->have_posts()) {
while($query->have_posts() ){
$query->the_post();
?>
<a href="<?php the_permalink(); ?>">
<div style="background-image:url('<?= get_field('case_picture'); ?>')">
<p><?= get_field('case_title') ?></p>
</div>
</a>
<?php }
}
die();
add_action('wp_ajax_nopriv_fetch_cases', 'fetch_cases');
add_action('wp_ajax_fetch_cases','fetch_cases');
}
And in my JS file have the following:
$.ajax({
url: "/wp-admin/admin-ajax.php",
data: {
action: "fetch_cases"
},
success: function(data) {
$(".fetch_cases").append(data);
},
error: function(errorThrown) {
console.log(errorThrown);
}
});
Can someone tell me what I'm doing wrong?
I also tried to do:
<?php the_field('case_picture'); ?>
but with no luck? what am I missing?
add_action() should be outside your custom function. Try this instead.
function fetch_cases(){
$args = array(
'post_type' => array('case'),
'post_status' => array('publish'),
'posts_per_page' => 5
);
$query = new WP_Query($args);
if($query->have_posts()) {
while($query->have_posts() ){
$query->the_post();
?>
<a href="<?php the_permalink(); ?>">
<div style="background-image:url('<?= get_field('case_picture'); ?>')">
<p><?= get_field('case_title') ?></p>
</div>
</a>
<?php }
}
die();
}
add_action('wp_ajax_nopriv_fetch_cases', 'fetch_cases');
add_action('wp_ajax_fetch_cases','fetch_cases');
you can use this logic by storing the field as a hidden value and pass in ajax through js
$query = new WP_Query($args);
if($query->have_posts()) {
while($query->have_posts() ){
$query->the_post();
?>
<a href="<?php the_permalink(); ?>">
<div style="background-image:url('<?= get_field('case_picture'); ?>')">
<p><?= get_field('case_title') ?></p>
<input type="hidden" id="hidden" name="hidden_field" value="<?= get_field('case_picture'); ?>"> // store the value
</div>
</a>
<?php }
}
die();
Now get the data in jquery and pass through ajax
<script>
var hidden=//Grab data here.
$.ajax({
url: "/wp-admin/admin-ajax.php",
data: {
action: "fetch_cases",
image:hidden, // Pass the data
},
success: function(data) {
$(".fetch_cases").append(data);
},
error: function(errorThrown) {
console.log(errorThrown);
}
});
</script>
and use the data in ajax called
function fetch_cases()
{
$image=$_POST['image'];
}
get_field method has 2nd parameter which is post ID, pass this and check. It should work.
$post_id = $post->ID;
$value = get_field( 'case_picture', $post_id );

how can i show this $data value in the form input field?

how to show $data value in form input field?
<head>
<script>
$(function () {
$("#task_id").change(function () {
var task_id = $(this).val();
var url = "status/tasks/get_task_info/" + task_id;
$.ajax({
url: url,
beforeSend: function () {
$(".load-taskinfo").html('<img src="images/ajax/ajax-loader10.gif">');
},
success: function (response) {
$data = JSON.parse(response);
}
});
});
});
</script>
</head>
<body>
<div class="span3">
<div class="control-group <?php echo (form_error('progress_percent')) ? 'error' : ''; ?>">
<label class="control-label" for="progress_percent">Progress (In %) :</label>
<div class="controls">
<?php echo form_input(array(
'name' => 'progress_percent',
'id' => 'progress_percent',
'maxlength' => 160
)); ?>
<?php if (form_error('progress_percent')) : ?>
<span class="help-inline">
<?php echo form_error('progress_percent'); ?>
</span>
<?php endif; ?>
</div>
</div>
</div>
</body>
In your success callback, use jQuery selector to select the input by ID or by name, and fill its value.
success: function (response) {
var $data = JSON.parse(response);
$('#progress_percent').val($data);
}

Saving data from a drop down list in CodeIgniter

I created a menu page where it has a drop down menu with a list of menus from the database and it also has a textbox to enter new menus.
The problem I'm having is that I can't seem to figure out how to save my dropdown. So for example I have a menu called "About Us" in the drop down list and I want to create a new menu called "Team", and "Team" is a child of "About Us"
So in my table I would have something like this
id | parent | title
------------------------
1 | NULL | About Us
2 | 1 | Team
Menu Controller
function get_data_from_post()
{
$data['title'] = $this->input->post('title', TRUE);
$data['parent'] = $this->input->post('parent', TRUE);
if(!isset($data)){
$data = '';
}
return $data;
}
function get_data_from_db($update_id)
{
$query = $this->get_where($update_id);
foreach($query->result() as $row){
$data['title'] = $row->title;
$data['parent'] = $row->parent;
}
return $data;
}
function create()
{
$update_id = $this->uri->segment(3);
$submit = $this->input->post('submit', TRUE);
if($submit == "Submit"){
//person has submitted the form
$data = $this->get_data_from_post();
}else{
if(is_numeric($update_id)){
$data = $this->get_data_from_db($update_id);
}
}
if(!isset($data)){
$data = $this->get_data_from_post();
}
//$titles = array();
$query = $this->get('title');
foreach($query->result() as $row){
$titles[] = $row->title;
}
$data['titles'] = $titles;
$data['update_id'] = $update_id;
$data['view_file'] = "create";
$this->load->module('templates');
$this->templates->admin_template($data);
}
function submit()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'required|xss_clean');
if($this->form_validation->run($this) == FALSE){
$this->create();
}else{
$data = $this->get_data_from_post();
$update_id = $this->uri->segment(3);
if(is_numeric($update_id)){
$this->_update($update_id, $data);
}else{
$this->_insert($data);
}
redirect('menus/manage');
}
}
create.php view
<div class="row">
<div class="col-md-12">
<h2>Create Menus</h2>
<h5>Welcome Jhon Deo , Need to make dynamic. </h5>
</div>
</div>
<hr />
<?php
echo validation_errors("<p style='color: red;'>", "</p>");
echo form_open('menus/submit/'.$update_id);
?>
<div class="row">
<div class="col-md-12">
<form role="form">
<div class="form-group">
<select name="menus">
<?php
foreach($titles as $title){
echo "<option value=".$title.">".$title."</option>";
}
?>
</select>
</div>
<div class="form-group">
<label>Title</label>
<!-- <input class="form-control" /> -->
<?php
$data = array(
'name' => 'title',
'id' => 'title',
'value' => $title,
'class' => 'form-control',
);
echo form_input($data);
?>
</div>
<?php
$data = array(
'name' => 'submit',
'id' => 'submit',
'value' => 'Submit',
'class' => 'btn btn-success',
'style' => 'width: 100%',
);
echo form_submit($data);
?>
</form>
</div>
</div>
<?php
echo form_close();
?>
UPDATE:
this is what I have when I print_r($titles)
Array
(
[0] => About Us
[1] => Home
)
If there is anything you don't understand or if you need me to give more information please let me know.
You should have declared a model. From there, you can create a function that will save the values in the database that you initialize via controller. You should utilize the MVC pattern of it. CodeIgniter has a great documentation to read about what I am pointing out.. https://codeigniter.com/user_guide/overview/mvc.html?highlight=model

Ajax form validation in codeigniter

hellp guys,
I've been working on ajax recently, and I have a problem in using it with codeigniter form validation library. I used the example that tool generate in the function http://formtorch.geekhut.org/.
Now, ajax works perfectly and return data correctly when I use json_encode() function with dummy data, but validation in the example uses validation library instead of form_validation library, which seems to be older version.
For that, validation didn't work with ajax in that example, specifically $this->form_validation->run() function makes ajax return no result even if I echo dummy data using json_encode() in the beginning of create_course().
so what's wrong with validation with ajax, and explain to me how data sent by ajax received by the controller.
so this is my code:
function create_course()
{
$this->form_validation->set_rules('course_code', 'course_code', 'trim|xss_clean|required');
$this->form_validation->set_rules('name', 'name', 'xss_clean|required');
// .. etc
if ($this->form_validation->run()) {
// validation ok
$data['course_code'] = $this->form_validation->set_value('course_code');
$data['name'] = $this->form_validation->set_value('name');
// ... etc
if ($this->models_facade->create_course($user_id,$data)) { // success
$data = array( 'profile_change' => $this->lang->line('profile_change'));
} else { // fail
$data = array( 'profile_change_error' => $this->lang->line('profile_change_error'));
}
}
else
{
$data = array(
'course_code' => $this->form_validation->course_code_error,
'name' => $this->form_validation->name_error
);
}
echo json_encode($data);
}
and this is the Jquery Ajax function
   $(function(){
$("#submit").click(function(){
var course_code = $("#course_code").val();
var name = $("#name").val();
// etc
$.post("<?php echo base_url() ?>home/create_course", course_code:course_code, name:name},
function(data){
function(data){
alert(data.data);
$("#course_code_error").html(data.course_code);
$("#name_error").html(data.name);
},'json');
});
return false;
});
   
Rather than printing out via "this->form_validation->xxxx_error" you can utilize Form Helper method "form_error()" to call the error messages.
So you can do something like..
$data = array(
'course_code' => form_error('course_code'),
'name' => form_error('name')
);
You might also consider setting the output content type header for JSON data.
$this->output->set_content_type('application/json');
echo json_encode($data);
What version of Codeigniter are you using? Did you remember to load the validation library in your construct?
$this->load->library('form_validation');
If you're making an ajax request you can use the validation_errors().
When the validation run it'll populate the array of error messages.
Here an exemple :
// Set your rules
$this->form_validation->set_rules('course_code', 'course_code', 'trim|xss_clean|required');
$this->form_validation->set_rules('name', 'name', 'xss_clean|required');
if ($this->form_validation->run()) {
//happy happy time
}
else {
//well now i'm sad...
//Important to turn that off if it's on
$this->output->enable_profiler(false);
$this->output->set_status_header('500');
$this->output->set_content_type('application/json');
echo json_encode(array(
'error_msg' => validation_errors(),
));
}
And then on your client-side you can use the response like that :
error:function(data) {
$("your-error-input-selector").html('').append(data.responseJSON.msg);
}
Hope i helped even if i'm 2 year late.
P.S Sorry for my broken english.
****//view-path [application/views/myviews/myview2.php]****
<script src="<?php echo base_url('/jquery-1.9.1.min.js');?>"></script>
<script>
$(document).ready(function() {
$("#frm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: $('#frm').attr('action'),
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log(data);
data = JSON.parse(data);
if(data.st == 0)
{
$( ".error-message" ).remove();
var data1 = JSON.parse(data.msg);
$('form :input').each(function(){
var elementName = $(this).attr('name');
var message = data1[elementName];
if(message){
var element = $('<div>' + message + '</div>')
.attr({
'class' : 'error-message'
})
.css ({
display: 'none'
});
$(this).before(element);
$(element).fadeIn();
}
});
}
if(data.st == 1)
{
$('#validation-error').html(data.msg);
$( ".error-message" ).remove();
}
},
error: function(){}
});
}));
});
</script>
<style>
.error-message{color:red;}
</style>
<?php echo form_open_multipart('ajaxcontroller/index', array('id'=>'frm')); ?>
<div id="validation-error"></div>
<h5>Username</h5>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />
<h5>Password</h5>
<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />
<h5>Password Confirm</h5>
<input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" />
<h5>Email Address</h5>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
<h5>Profile Pic</h5>
<input type="file" name="image[]" value="" multiple=""/>
<div><input type="submit" value="Submit" /></div>
</form>
**//controller--[application/controllers/ajaxcontroller.php]****
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ajaxcontroller extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
if($_POST)
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]');
$this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if (empty($_FILES['image']['name'][0])) {
$this->form_validation->set_rules('image[]', 'File', 'required');
}
if ($this->form_validation->run() == FALSE)
{
$errors = $this->form_validation->error_array(); //function in library : My_Form_validation
echo json_encode(array('st'=>0, 'msg' => json_encode($errors)));
}
else
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$email = $this->input->post('email');
if(is_array($_FILES)) {
foreach ($_FILES['image']['name'] as $name => $value){
if(is_uploaded_file($_FILES['image']['tmp_name'][$name])) {
$sourcePath = $_FILES['image']['tmp_name'][$name];
$targetPath = "images/".$_FILES['image']['name'][$name];
if(move_uploaded_file($sourcePath,$targetPath)) {
}
}
}
}
echo json_encode(array('st'=>1, 'msg' => 'Successfully Submiited'));
}
}
else
{
$this->load->view('myviews/myview2');
}
}
}
**//library file -- path will be [application/libraries/MY_Form_validation.php]**
<?php
/**
*
* Enter description here ...
* #return CI_Controller
*/
class MY_Form_validation extends CI_Form_validation
{
public function error_array()
{
return $this->_error_array;
}
}

Resources