How to use jquery validation (ajax) using Codeigniter
Validation form is very useful when we are checking on the client side. there are lots of methods are available for validation.
As you can see to pass through data you can simply use the key pair syntax so the request sent below the data is “&emails=youremail@address”. The return values for your backend is true and false.
We’re going to use the jQuery Validation Plugin to validate our form. The basic principle of this plugin is to specify validation rules and error messages for HTML elements in JavaScript.
HTML Code
<form action="#" id="add-user" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Full Name <span style="color: #F00">*</span></label>
<input type="text" name="fullname" class="form-control" maxlength="32" autofocus autocomplete="off" />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Email Address <span style="color: #F00">*</span></label>
<input type="email" name="email" class="form-control" maxlength="32" autocomplete="off" />
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Mobile </label>
<input type="text" name="mobile" class="form-control" maxlength="32" autofocus autocomplete="off" />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Address </label>
<textarea name="address" id="address" class="form-control" ></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group ">
<input type="submit" class="btn btn-primary text-center" value="Add New" />
</div>
</div>
</div>
</form>
Jquery / JavaScript Code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://scripts.guru/download/jquery.validate.min.js"></script>
<script type="text/javascript">
$(function() {
$("#add-user").validate({
rules: {
fullname:"required",
email: {
required: true,
email: true,
remote: {
url: "Checkemail", type: "post" } }, }, messages: { fullname: "Please enter your Full Name", email:{ required: "Please provide a Email", remote: "Email already in use!", }, }, submitHandler: function(form) { form.submit(); } }); }); </script>
Remote Call in Controller (function Checkemail
())
public function Checkemail()
{
$requestedEmail = $this->input->post('email');
$getemail = $this->db->get_where('users',array('email' => $requestedEmail))->num_rows();
if($getemail == 0)
{
echo 'true';
}
else
{
echo 'false';
}
}
Leave a Reply