Codeigniter Ajax Form Validation Example
Today, I would like to share with you how to create jquery ajax form validation in codeigniter 3 app. Here i will create simple form and make it server side validation using form_validation library. form_validation will help to easily set custom rule, success, error messages.
Validation is very important part of every project. If you are doing login form, registration form, contact us form, comments etc. You must require to set form validation. Codeigniter provide form_validation library for set server side validation, but if we make it simple then it always refresh page, so it would be better if you use jquery ajax for form validation.
So here i gave you full example of form validation in codeigniter application. i created simple form with first name, last name, email and address like contact us form and i set server side validation using ajax. So let's simple see bellow step and make it ajax validation quick.
Step 1: Create Routes
In first step we require to add two route for display form and post form. so open routes.php file and add code like as bellow:
application/config/routes.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['item'] = "item/index";
$route['itemForm'] = "item/itemForm";
Step 2: Create Item Controller
In this step, we need to create Item Controller and define two methods, index() and itemForm(), Here we will also load form_validation and session library. So let's proceed.
application/controllers/Item.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Item extends CI_Controller {
/**
* Get All Data from this method.
*
* @return Response
*/
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->library('session');
}
/**
* Create from display on this method.
*
* @return Response
*/
public function index()
{
$this->load->view('item');
}
/**
* Store Data from this method.
*
* @return Response
*/
public function itemForm()
{
$this->form_validation->set_rules('first_name', 'First Name', 'required');
$this->form_validation->set_rules('last_name', 'Last Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('address', 'Address', 'required');
if ($this->form_validation->run() == FALSE){
$errors = validation_errors();
echo json_encode(['error'=>$errors]);
}else{
echo json_encode(['success'=>'Record added successfully.']);
}
}
}
Step 3: Create View File
In last step, we need to create view file, So here create item.php view file and copy bellow code, here we will display form.
application/views/item.php
<!DOCTYPE html>
<html>
<head>
<title>Codeigniter Ajax Validation Example</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
</head>
<body>
<div class="container">
<h2>Codeigniter Ajax Validation</h2>
<div class="alert alert-danger print-error-msg" style="display:none">
</div>
<form>
<div class="form-group">
<label>First Name:</label>
<input type="text" name="first_name" class="form-control" placeholder="First Name">
</div>
<div class="form-group">
<label>Last Name:</label>
<input type="text" name="last_name" class="form-control" placeholder="Last Name">
</div>
<div class="form-group">
<strong>Email:</strong>
<input type="text" name="email" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<strong>Address:</strong>
<textarea class="form-control" name="address" placeholder="Address"></textarea>
</div>
<div class="form-group">
<button class="btn btn-success btn-submit">Submit</button>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
$(".btn-submit").click(function(e){
e.preventDefault();
var _token = $("input[name='_token']").val();
var first_name = $("input[name='first_name']").val();
var last_name = $("input[name='last_name']").val();
var email = $("input[name='email']").val();
var address = $("textarea[name='address']").val();
$.ajax({
url: "/itemForm",
type:'POST',
dataType: "json",
data: {first_name:first_name, last_name:last_name, email:email, address:address},
success: function(data) {
if($.isEmptyObject(data.error)){
$(".print-error-msg").css('display','none');
alert(data.success);
}else{
$(".print-error-msg").css('display','block');
$(".print-error-msg").html(data.error);
}
}
});
});
});
</script>
</body>
</html>
Now we are ready to this full example.
So let's run bellow command on your root directory for quick run:
php -S localhost:8000
Now you can open bellow URL on your browser:
http://localhost:8000/item
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- PHP Ajax Form Validation Example Tutorial
- Codeigniter Image Upload with Validation Example
- Codeigniter Ajax CRUD Tutorial Example
- Laravel 5.3 - Form Input Validation rules example with demo
- Codeigniter Select2 Ajax Autocomplete from Database Example
- Laravel Client Side Validation using Parsley.js Example
- Codeigniter 3 and AngularJS CRUD with Search and Pagination Example.