Sunteți pe pagina 1din 3

PHP Codeigniter 3 - JQuery Ajax Form Validation Example

It is very simple to use ajax validation with codeigniter. Here i explain every thing step by
step for implement ajax validation. So you can see following steps and check how it works.

Step 1: Create Routes

In first step, we need to add routes to handle ajax request and display the form.

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['ajax-form-validation'] = "AjaxFormValidation";
$route['ajax-form-validation/post']['post'] =
"AjaxFormValidation/validationForm";

Step 2: Create Controller Class

In second step, we will create a controller "AjaxFormValidation.php" and write code of get
method and post method.

application/controllers/AjaxFormValidation.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class AjaxFormValidation 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('ajax_form_validation');
}

/**
* Validate and store the form data.
*
* @return Response
*/
public function validationForm()
{
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email',
'required|valid_email');
$this->form_validation->set_rules('message', 'Message',
'required');

if ($this->form_validation->run() == FALSE){
$errors = validation_errors();
echo json_encode(['error'=>$errors]);
}else{
echo json_encode(['success'=>'Form submitted successfully.']);
}
}
}

Step 3: Add View File

In last step. we need to create ajax_form_validation.php file for view. In this file we will
write code for create form and jquery ajax code.

application/views/ajax_form_validation.php

<html>
<head>
<title>PHP Codeigniter 3 - JQuery Ajax Form Validation Example-
HDTuto.com</title>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/twitter-
bootstrap/4.1.1/css/bootstrap.min.css" />
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></s
cript>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<div class="alert alert-danger" style="display:none">
</div>

<?php echo form_open('ajax-form-validation/post');?>


<div class="form-group">
<label>Name:</label>
<input type="text" name="name" class="form-control"
placeholder="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>Message:</strong>
<textarea class="form-control" name="message"
placeholder="Message"></textarea>
</div>

<div class="form-group">
<button class="btn btn-primary btn-block btn-
submit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</body>

<script type="text/javascript">
$(document).ready(function() {
$(".btn-submit").click(function(e){
e.preventDefault();
var name = $("input[name='name']").val();
var email = $("input[name='email']").val();
var message = $("textarea[name='message']").val();
$.ajax({
url: $(this).closest('form').attr('action'),
type:$(this).closest('form').attr('method'),
dataType: "json",
data: {name:name, email:email, message:message},
success: function(data) {
if($.isEmptyObject(data.error)){
$(".alert-danger").css('display','none');
alert(data.success);
}else{
$(".alert-danger").css('display','block');
$(".alert-danger").html(data.error);
}
}
});
});
});
</script>

</html>

Now you can run this example and check it.

I hope you found your best solution....

data: { '<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo


$this->security->get_csrf_hash(); ?>',data }

S-ar putea să vă placă și