Skip to content
  • Github
  • Facebook
  • twitter
  • About Us
  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Site Map

XpertPhp

Expertphp Is The Best Tutorial For Beginners

  • Home
  • Javascript
    • Jquery
    • React JS
    • Angularjs
    • Angular
    • Nodejs
  • Codeigniter
  • Laravel
  • Contact Us
  • About Us
  • Live Demos
CodeIgniter 4 Ajax Form Submit Validation Example

CodeIgniter 4 Ajax Form Submit Validation Example

Posted on August 16, 2021December 14, 2022 By XpertPhp

In this article, we will explain to you how to create an ajax form submit validation in CodeIgniter 4(CodeIgniter 4 Ajax Form Submit Validation Example). we can easily create the ajax form validation in CodeIgniter 4. so here in this example, we use the jquery library with submitHandler function for form validation.

You can use the Codeigniter validation library or jquery validation for form validation. But sometimes we need to without reloading the page the submit form and validation. so here we use the ajax form to submit validation in CodeIgniter 4.
Overview
Step 1: Download Codeigniter
Step 2: Basic Configurations
Step 3: Create a Database in table
Step 4: Connect to Database
Step 5: Create Controller and Model
Step 6: Create Views Files
Step 7: Run The Application

Step 1: Download Codeigniter
If you want to download or install the latest version of CodeIgniter 4 then you can go to Codeigniter’s official site and download the latest version of Codeigniter 4. after the downloaded you can configure in “xampp/htdocs/” directory.

Step 2: Basic Configurations
If you want to Basic Configurations in your project then you can below Url.
Codeigniter 4 Removing Index.Php From Url

Step 3: Create a Database in table
In this step, We will create the database and table.

1
2
3
4
5
6
7
8
9
CREATE TABLE IF NOT EXISTS `students` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(64) NOT NULL,
  `last_name` varchar(64) NOT NULL,
  `address` text NOT NULL,
  `email` varchar(64) NOT NULL,
  `mobile` varchar(12) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;

Step 4: Connect to Database
Go to the “app/Config/Database.php” folder and open the database.php file some changes in this file like hostname, database username, database password, and database name.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public $default = [
'DSN'      => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'codeigniter4_jqurey_validation',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug'  => (ENVIRONMENT !== 'production'),
'cacheOn'  => false,
'cacheDir' => '',
'charset'  => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre'  => '',
'encrypt'  => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port'     => 3306,
];

Step 5: Create Controller and Model
In this step, we will create the “Student.php” controller and the “StudentModel.php” model.
app/Controllers/Student.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
 
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\StudentModel;
class Student extends Controller
{
public function __construct()
    {
        helper(['form', 'url']);
    }
    public function index()
    {    
        return view('add');
    }    
    public function store()
    {  
$data = [
'first_name' => $this->request->getVar('txtFname'),
'last_name'  => $this->request->getVar('txtLname'),
'email'  => $this->request->getVar('txtEmail'),
'mobile'  => $this->request->getVar('txtMobile'),
'address'  => $this->request->getVar('txtAddress'),
];
$model = new StudentModel();
$save = $model->insert($data);
$resData = [
'success' => true,
'data' => $save,
'msg' => "Student has been added successfully"
];
 
return $this->response->setJSON($resData);
    }
}
 
?>

app/Models/StudentModel.php

1
2
3
4
5
6
7
8
9
10
11
<?php namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
class StudentModel extends Model
{
    protected $table = 'Students';
    protected $allowedFields = ['first_name','last_name','address','email', 'mobile'];
}
?>

Step 6: Create Views Files
Finally, we will create the add.php in the app/views directory.

app/views/add.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<!DOCTYPE html>
<html>
<head>
  <title>CodeIgniter 4 Ajax Form Submit Validation Example - XpertPhp</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-9">
<h2>Add Student</h2>
</div>
</div>
    <div class="row">
      <div class="col-md-9">
        <form method="post" name="frmAddStudent" id="frmAddStudent" action="<?php echo site_url('student/store');?>">
          <div class="form-group">
            <label for="txtFname">First Name</label>
<input type="text" name="txtFname" class="form-control" id="txtFname" placeholder="Please enter first name" />
          </div>
   <div class="form-group">
            <label for="txtLname">Last Name</label>
<input type="text" name="txtLname" class="form-control" id="txtLname" placeholder="Please enter last name" />
          </div>
          <div class="form-group">
            <label for="txtEmail">Email</label>
<input type="text" name="txtEmail" class="form-control" id="txtEmail" placeholder="Please enter email" />
          </div>
<div class="form-group">
            <label for="txtMobile">Mobile</label>
<input type="text" name="txtMobile" class="form-control" id="txtMobile" placeholder="Please enter mobile number." />
          </div>   
          <div class="form-group">
            <label for="txtAddress">Address</label>
<textarea name="txtAddress" class="form-control"></textarea>
          </div>
          <div class="form-group">
   <input type="submit" value="Add" name="btnadd" id="btnadd" class="btn btn-success" />
          </div>
        </form>
      </div>
    </div>
<span class="d-none alert alert-success mb-3" id="res_message"></span>
</div>
<script>
   if ($("#frmAddStudent").length > 0) {
      $("#frmAddStudent").validate({
    rules: {
      txtFname: {
        required: true,
      },
  txtLname: {
        required: true,
      },
      txtEmail: {
        required: true,
        maxlength: 50,
        email: true,
      },
  txtMobile: {
        required: true,
number: true,
        maxlength: 12,
      },
      txtAddress: {
        required: true,
      },  
    },
    messages: {
      txtFname: {
        required: "Please enter first name",
      },
   txtLname: {
        required: "Please enter last name",
      },
      txtEmail: {
        required: "Please enter valid email",
        email: "Please enter valid email",
        maxlength: "The email name should less than or equal to 50 characters",
     },      
txtMobile: {
        required: "Please enter mobile number",
number:"Please enter numbers Only",
maxlength: "The mobile number should less than or equal to 12 characters",
     },
     txtAddress: {
        required: "Please enter address",
     },
    },
submitHandler: function(form) {
$('#btnadd').val('Sending..');
$.ajax({
url: "<?php echo site_url('student/store') ?>",
type: "POST",
data: $('#frmAddStudent').serialize(),
dataType: "json",
success: function(response) {
console.log(response);
console.log(response.success);
$('#btnadd').val('Add');
$('#res_message').html(response.msg);
$('#res_message').show();
$('#res_message').removeClass('d-none');
$('#frmAddStudent')[0].reset();
setTimeout(function() {
$('#res_message').hide();
$('#res_message').html('');
}, 3000);
}
});
}
    })
}
</script>
</body>
</html>
See also  How To Use Multiple Database In Codeigniter

Step 7: Run The Application
We can start the server and run the codeigniter 4 application using the below command.

1
php spark serve

Now we will run our example using the below Url in the browser.

1
http://localhost:8080/student

If you liked this article, you can also download it through our Github Repository.

Read Also
Codeigniter 4 CRUD Operation With Ajax Example
CodeIgniter 4 jQuery Form Validation Example Tutorial
CodeIgniter 4 Form Validation Example Tutorial

Codeigniter, Ajax Tags:Codeigniter 4 Tutorial

Post navigation

Previous Post: CodeIgniter 4 jQuery Form Validation Example Tutorial
Next Post: CodeIgniter 4 Image Upload With Preview Example

Latest Posts

  • Laravel 12 Ajax CRUD Example
  • Laravel 12 CRUD Example Tutorial
  • How to Create Dummy Data in Laravel 11
  • Laravel 11 Yajra Datatables Example
  • Laravel 11 Ajax CRUD Example
  • Laravel 11 CRUD Example Tutorial
  • Laravel 10 Ajax CRUD Example Tutorial
  • Laravel 10 CRUD Example Tutorial
  • How to disable button in React js
  • JavaScript Interview Questions and Answers

Tools

  • Compound Interest Calculator
  • Hex to RGB Color Converter
  • Pinterest Video Downloader
  • Birthday Calculator
  • Convert JSON to PHP Array Online
  • JavaScript Minifier
  • CSS Beautifier
  • CSS Minifier
  • JSON Beautifier
  • JSON Minifier

Categories

  • Ajax
  • Angular
  • Angularjs
  • Bootstrap
  • Codeigniter
  • Css
  • Htaccess
  • Interview
  • Javascript
  • Jquery
  • Laravel
  • MongoDB
  • MySql
  • Nodejs
  • Php
  • React JS
  • Shopify Api
  • Ubuntu

Tags

angular 10 tutorial angular 11 ci tutorial codeigniter 4 image upload Codeigniter 4 Tutorial codeigniter tutorial CodeIgniter tutorial for beginners codeigniter with mysql crud operation eloquent relationships file upload File Validation form validation Image Upload jQuery Ajax Form Handling jquery tutorial laravel 6 Laravel 6 Eloquent Laravel 6 Model laravel 6 relationship laravel 6 relationship eloquent Laravel 6 Routing laravel 7 Laravel 7 Eloquent laravel 7 routing laravel 7 tutorial Laravel 8 laravel 8 example laravel 8 tutorial laravel 9 example laravel 9 tutorial Laravel Framework laravel from scratch laravel social login learn jquery nodejs pagination payment gateway php with mysql react js example react js tutorial send mail validation wysiwyg editor wysiwyg html editor

Copyright © 2018 - 2025,

All Rights Reserved Powered by XpertPhp.com