{"id":7282,"date":"2021-12-06T03:52:10","date_gmt":"2021-12-06T03:52:10","guid":{"rendered":"https:\/\/programmingfields.com\/?p=7282"},"modified":"2026-05-02T06:29:31","modified_gmt":"2026-05-02T06:29:31","slug":"codeigniter-4-ajax-form-handling-with-form-validation","status":"publish","type":"post","link":"https:\/\/programmingfields.com\/codeigniter-4-ajax-form-handling-with-form-validation\/","title":{"rendered":"CodeIgniter 4 Ajax Form Handling With Form Validation"},"content":{"rendered":"\n<p>Ajax provides a technique to handle the form request without reloading the page. You can use <strong>Ajax in CodeIgniter 4<\/strong> for handling form data. This will allow you to validate and submit your form without refreshing it. This is used at the client-side to handle the client request in the browser. If you are working on PHP technology then while creating a web application, it is always required to use Ajax. Even you can handle the API request at the client-side using Ajax. Today, in this post, I will be showing you the use of <strong>Ajax in CodeIgniter 4<\/strong>. In this demo project, I will create a basic form and I will validate it. After the successful validation, it will be submitted on the given action through Ajax. Here, in the entire process, the form won&#8217;t refresh on the submit.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-light-blue ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/programmingfields.com\/codeigniter-4-ajax-form-handling-with-form-validation\/#Prerequisites\" >Prerequisites<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/programmingfields.com\/codeigniter-4-ajax-form-handling-with-form-validation\/#Create_Project_For_Ajax_Form_Handling_in_Codeigniter_4\" >Create Project For Ajax Form Handling in Codeigniter 4<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/programmingfields.com\/codeigniter-4-ajax-form-handling-with-form-validation\/#Configure_Project_Environment_in_CodeIgniter_4\" >Configure Project Environment in CodeIgniter 4<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/programmingfields.com\/codeigniter-4-ajax-form-handling-with-form-validation\/#Configure_Database_in_Codeigniter_4\" >Configure Database in Codeigniter 4<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/programmingfields.com\/codeigniter-4-ajax-form-handling-with-form-validation\/#Create_a_Migration_in_CodeIgniter_4\" >Create a Migration in CodeIgniter 4<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/programmingfields.com\/codeigniter-4-ajax-form-handling-with-form-validation\/#Create_a_Model_in_CodeIgniter_4_For_Ajax_Form_Handling\" >Create a Model in CodeIgniter 4 For Ajax Form Handling<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/programmingfields.com\/codeigniter-4-ajax-form-handling-with-form-validation\/#Create_a_View_in_CodeIgniter_4_For_Ajax_Form_Handling\" >Create a View in CodeIgniter 4 For Ajax Form Handling<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/programmingfields.com\/codeigniter-4-ajax-form-handling-with-form-validation\/#Create_a_Controller_For_Ajax_Form_Handling_in_CodeIgniter_4\" >Create a Controller For Ajax Form Handling in CodeIgniter 4<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/programmingfields.com\/codeigniter-4-ajax-form-handling-with-form-validation\/#Create_Routes_in_CodeIgniter_4\" >Create Routes in CodeIgniter 4<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/programmingfields.com\/codeigniter-4-ajax-form-handling-with-form-validation\/#Check_Results_of_CodeIgniter_AJAX_Form_Handling\" >Check Results of CodeIgniter AJAX Form Handling<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/programmingfields.com\/codeigniter-4-ajax-form-handling-with-form-validation\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Prerequisites\"><\/span><strong>Prerequisites<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>We are going to work on CodeIgniter 4. Hence, in order to create a new project, you may download the setup directly from the official website of CodeIgniter. But, I will use composer dependency manager. So, you can ahead with composer, if you already installed it in your system.<\/p>\n\n\n\n<p>Also, you will require the below configuration for the CodeIgniter 4 project setup.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>PHP &gt;= 7.3<\/strong><\/li>\n\n\n\n<li><strong>MySQL (version &gt; 5)<\/strong><\/li>\n\n\n\n<li><strong>Apache\/Nginx Server<\/strong><\/li>\n\n\n\n<li><strong>VS Code Editor<\/strong><\/li>\n\n\n\n<li><strong>Composer<\/strong><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_Project_For_Ajax_Form_Handling_in_Codeigniter_4\"><\/span><strong>Create Project For Ajax Form Handling in Codeigniter 4<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>At the very first, open the terminal or command prompt whatever you have. Then hit the below command for installing the latest version of CodeIgniter.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">composer create-project codeigniter4\/appstarter ci4-ajax<\/code><\/pre>\n\n\n\n<p>The above command will take a couple of minutes to install the CodeIgniter project in your system. Once, it is done, you will need to configure the environment for the project.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Configure_Project_Environment_in_CodeIgniter_4\"><\/span><strong>Configure Project Environment in CodeIgniter 4<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Before implementing any functionality in CodeIgniter 4, you will need to configure the environment. Therefore, open the project in the VS code editor. Now, inside the project directory, look for the <strong>env<\/strong> file. Initially, you will need to rename it to&nbsp;<strong>.env<\/strong>. Now, open this file and search for the&nbsp;<strong>Environment configuration<\/strong> inside the <strong>.env<\/strong> file.<\/p>\n\n\n\n<p>Under the environment section, by default, the environment will be <strong>production<\/strong>. Hence, in order to work on the local system, this will require to be renamed as <strong>development<\/strong>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">#--------------------------------------------------------------------\n# ENVIRONMENT\n#--------------------------------------------------------------------\n\nCI_ENVIRONMENT = development<\/code><\/pre>\n\n\n\n<p>In the next step, you will have to setup the database for the project. So, that we can work on the form handling and submitting the data into the table.<\/p>\n\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/programmingfields.com\/login-and-registration-authentication-in-codeigniter-4\/\" target=\"_blank\" rel=\"noreferrer noopener\">Login and Registration Authentication in Codeigniter 4<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Configure_Database_in_Codeigniter_4\"><\/span><strong>Configure Database in Codeigniter 4<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Before going to the database configuration, create a database in MySQL first. After that come to the CodeIgniter 4 project. Again go inside the <strong>.env <\/strong>file and under the database section, configure the credentials as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">#--------------------------------------------------------------------\n# DATABASE\n#--------------------------------------------------------------------\n\ndatabase.default.hostname = localhost\ndatabase.default.database = ci4_ajax\ndatabase.default.username = root\ndatabase.default.password = root\ndatabase.default.DBDriver = MySQLi<\/code><\/pre>\n\n\n\n<p>That&#8217;s it for the database configuration. Now, let&#8217;s create a migration file for the table(s).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_a_Migration_in_CodeIgniter_4\"><\/span><strong>Create a Migration in CodeIgniter 4<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>For creating a new migration, I will use the spark command. It will generate the migration file. I will create one table in which I will store some values using <strong>CodeIgniter AJAX form handling<\/strong>. Hence, let&#8217;s create a migration file using the below command. Open the terminal inside the project folder, and now hit the below command.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">php spark make:migration ajaxForms<\/code><\/pre>\n\n\n\n<p>When the migration is created, it will return the below response.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"91\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-04-08-57-04.png?resize=1024%2C91&#038;ssl=1\" alt=\"Create Migration For Ajax Form\" class=\"wp-image-7300\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-04-08-57-04.png?resize=1024%2C91&amp;ssl=1 1024w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-04-08-57-04.png?resize=300%2C27&amp;ssl=1 300w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-04-08-57-04.png?resize=768%2C68&amp;ssl=1 768w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-04-08-57-04.png?w=1161&amp;ssl=1 1161w\" sizes=\"auto, (max-width: 1000px) 100vw, 1000px\" \/><figcaption class=\"wp-element-caption\"><strong>Create Migration For Ajax Form<\/strong><\/figcaption><\/figure>\n<\/div>\n\n\n<p>Now, come to the <strong>app\/Config\/Database\/Migrations<\/strong> folder and you will have the created migration file. In our case, we have the <strong>timestamp_Ajaxforms.php<\/strong> file.<\/p>\n\n\n\n<p>Open that file, and replace it with the below schema.<\/p>\n\n\n\n<pre title=\"timestamp_Ajaxforms.php\" class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">&lt;?php\n\nnamespace App\\Database\\Migrations;\n\nuse CodeIgniter\\Database\\Migration;\n\nclass Ajaxforms extends Migration\n{\n\tpublic function up()\n\t{\n\t\t$this-&gt;forge-&gt;addField([\n            'id' =&gt; [\n                'type' =&gt; 'INT',\n                'auto_increment' =&gt; true\n            ],\n            'name' =&gt; [\n                'type' =&gt; 'VARCHAR',\n                'constraint' =&gt; '100'\n            ],\n\t\t\t'email' =&gt; [\n\t\t\t\t'type' =&gt; 'VARCHAR',\n\t\t\t\t'constraint' =&gt; '255'\n\t\t\t],\n\t\t\t'password' =&gt; [\n\t\t\t\t'type' =&gt; 'VARCHAR',\n\t\t\t\t'constraint' =&gt; '255'\n\t\t\t],\n\t\t\t'phone' =&gt; [\n\t\t\t\t'type' =&gt; 'VARCHAR',\n\t\t\t\t'constraint' =&gt; '255'\n\t\t\t],\n\t\t\t'address' =&gt; [\n\t\t\t\t'type' =&gt; 'VARCHAR',\n\t\t\t\t'constraint' =&gt; '255'\n\t\t\t],\n            'created_at datetime default current_timestamp',\n            'updated_at datetime default current_timestamp on update current_timestamp'\n        ]);\n        $this-&gt;forge-&gt;addKey('id', true);\n        $this-&gt;forge-&gt;createTable('ajaxForms');\n\t}\n\n\tpublic function down()\n\t{\n\t\t$this-&gt;forge-&gt;dropTable('ajaxForms');\n\t}\n}\n<\/code><\/pre>\n\n\n\n<p>Here, we defined the schema for the <strong>ajaxForms<\/strong> table. This table will need to be generated inside the database. Hence, in order to do that, you will need to migrate this table. Therefore, hit the below command in the terminal.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">php spark migrate<\/code><\/pre>\n\n\n\n<p>This will generate the table along with its schema.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"991\" height=\"138\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-04-08-59-02.png?resize=991%2C138&#038;ssl=1\" alt=\"Migrate Tables\" class=\"wp-image-7302\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-04-08-59-02.png?w=991&amp;ssl=1 991w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-04-08-59-02.png?resize=300%2C42&amp;ssl=1 300w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-04-08-59-02.png?resize=768%2C107&amp;ssl=1 768w\" sizes=\"auto, (max-width: 991px) 100vw, 991px\" \/><figcaption class=\"wp-element-caption\"><strong>Migrate Tables<\/strong><\/figcaption><\/figure>\n<\/div>\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/programmingfields.com\/send-email-in-codeigniter-4-using-smtp\/\" target=\"_blank\" rel=\"noreferrer noopener\">How to Send Email in CodeIgniter 4 Using Gmail SMTP<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_a_Model_in_CodeIgniter_4_For_Ajax_Form_Handling\"><\/span><strong>Create a Model in CodeIgniter 4 For Ajax Form Handling<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In Codeigniter 4, you can create a model using the spark command. So, in the same terminal, hit the below command.<\/p>\n\n\n\n<pre title=\"\" class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">php spark make:model AjaxForm<\/code><\/pre>\n\n\n\n<p>The above command will generate a model file. Inside the created model, you will need to configure the table name as per the migration and also the allowed fields array. The allowed fields will accept the value for the defined fields inside the table.<\/p>\n\n\n\n<pre title=\"Ajaxform.php\" class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">&lt;?php\n\nnamespace App\\Models;\n\nuse CodeIgniter\\Model;\n\nclass Ajaxform extends Model\n{\n\tprotected $DBGroup            = \t'default';\n\tprotected $table              = \t'ajaxForms';\n\tprotected $primaryKey         = \t'id';\n\tprotected $useAutoIncrement   = \ttrue;\n\tprotected $protectFields      = \ttrue;\n\tprotected $allowedFields      = \t['name', 'email', 'password', 'address'];\n\n\t\/\/ Dates\n\tprotected $useTimestamps      = \tfalse;\n\tprotected $dateFormat         = \t'datetime';\n\tprotected $createdField       = \t'created_at';\n\tprotected $updatedField       = \t'updated_at';\n}\n<\/code><\/pre>\n\n\n\n<p>That&#8217;s it for the model, and migration setup. Now, in the next step, you will require a view. The view will contain a basic form with some input fields.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_a_View_in_CodeIgniter_4_For_Ajax_Form_Handling\"><\/span><strong>Create a View in CodeIgniter 4 For Ajax Form Handling<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>For creating a view, come under the <strong>app\/Views<\/strong> folder. Now, create a new file with the name <strong>ajax-form.php<\/strong>. Now, add the below snippet inside it.<\/p>\n\n\n\n<pre title=\"ajax-form.php\" class=\"wp-block-code\"><code lang=\"javascript\" class=\"language-javascript\">&lt;!doctype html&gt;\n&lt;html lang=\"en\"&gt;\n\n&lt;head&gt;\n    &lt;title&gt;Codeigniter 4 Ajax Form Handling&lt;\/title&gt;\n    &lt;meta charset=\"utf-8\"&gt;\n    &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"&gt;\n\n    &lt;!-- bootstrap 5 CSS --&gt;\n    &lt;link href=\"https:\/\/cdn.jsdelivr.net\/npm\/bootstrap@5.0.0-beta3\/dist\/css\/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-eOJMYsd53ii+scO\/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6\" crossorigin=\"anonymous\"&gt;\n    &lt;link rel=\"stylesheet\" href=\"https:\/\/cdn.jsdelivr.net\/npm\/bootstrap-icons@1.4.1\/font\/bootstrap-icons.css\"&gt;\n    &lt;style&gt;\n        .error {\n            color: #dc3545;\n        }\n    &lt;\/style&gt;\n&lt;\/head&gt;\n\n&lt;body&gt;\n    &lt;div class=\"container py-4\"&gt;\n        &lt;div class=\"row\"&gt;\n            &lt;div class=\"col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto\"&gt;\n                &lt;form method=\"POST\" action=\"javascript:void(0)\" id=\"registrationForm\"&gt;\n                    &lt;?= csrf_field() ?&gt;\n\n                    &lt;div class=\"card shadow\"&gt;\n                        &lt;div class=\"card-header\"&gt;\n                            &lt;h5 class=\"card-title\"&gt;Codeigniter 4 Ajax Form Handling&lt;\/h5&gt;\n                        &lt;\/div&gt;\n\n                        &lt;div class=\"card-body p-4\"&gt;\n\n                            &lt;div class=\"form-group mb-3 has-validation\"&gt;\n                                &lt;label class=\"form-label\" for=\"name\"&gt;Name&lt;\/label&gt;\n                                &lt;input type=\"text\" class=\"form-control\" id=\"name\" name=\"name\" placeholder=\"Name\" value=\"&lt;?php echo set_value('name'); ?&gt;\" \/&gt;\n                            &lt;\/div&gt;\n\n                            &lt;div class=\"form-group mb-3\"&gt;\n                                &lt;label class=\"form-label\" for=\"email\"&gt;Email&lt;\/label&gt;\n                                &lt;input type=\"text\" class=\"form-control\" name=\"email\" id=\"email\" placeholder=\"Email\" value=\"&lt;?php echo set_value('email'); ?&gt;\" \/&gt;\n                            &lt;\/div&gt;\n\n                            &lt;div class=\"form-group mb-3\"&gt;\n                                &lt;label class=\"form-label\" for=\"password\"&gt;Password&lt;\/label&gt;\n                                &lt;input type=\"password\" class=\"form-control\" id=\"password\" name=\"password\" placeholder=\"Password\" value=\"&lt;?php echo set_value('password'); ?&gt;\" \/&gt;\n                            &lt;\/div&gt;\n\n                            &lt;div class=\"form-group mb-3\"&gt;\n                                &lt;label class=\"form-label\" for=\"confirm_password\"&gt;Confirm Password&lt;\/label&gt;\n                                &lt;input type=\"password\" class=\"form-control\" id=\"confirm_password\" name=\"confirm_password\" placeholder=\"Confirm Password\" value=\"&lt;?php echo set_value('confirm_password'); ?&gt;\" \/&gt;\n                            &lt;\/div&gt;\n\n                            &lt;div class=\"form-group mb-3\"&gt;\n                                &lt;label class=\"form-label\" for=\"phone\"&gt;Phone&lt;\/label&gt;\n                                &lt;input type=\"text\" class=\"form-control\" id=\"phone\" name=\"phone\" placeholder=\"Phone\" value=\"&lt;?php echo set_value('phone'); ?&gt;\" \/&gt;\n                            &lt;\/div&gt;\n\n                            &lt;div class=\"form-group\"&gt;\n                                &lt;label class=\"form-label\" for=\"address\"&gt;Address&lt;\/label&gt;\n                                &lt;textarea class=\"form-control\" name=\"address\" id=\"address\" placeholder=\"Address\"&gt;&lt;?php echo set_value('address'); ?&gt;&lt;\/textarea&gt;\n                            &lt;\/div&gt;\n                        &lt;\/div&gt;\n\n                        &lt;div class=\"card-footer d-flex align-items-center\"&gt;\n                            &lt;button type=\"submit\" id=\"submit-btn\" class=\"btn btn-success\"&gt;Save&lt;\/button&gt;\n\n                            &lt;div class=\"response-message ms-3\"&gt;&lt;\/div&gt;\n                        &lt;\/div&gt;\n                    &lt;\/div&gt;\n                &lt;\/form&gt;\n            &lt;\/div&gt;\n        &lt;\/div&gt;\n    &lt;\/div&gt;\n\n    &lt;script src=\"https:\/\/code.jquery.com\/jquery-3.6.0.min.js\" integrity=\"sha256-\/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej\/m4=\" crossorigin=\"anonymous\"&gt;&lt;\/script&gt;\n    &lt;script src=\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/jquery-validate\/1.19.0\/jquery.validate.js\"&gt;&lt;\/script&gt;\n    &lt;script src=\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/jquery-validate\/1.19.0\/additional-methods.min.js\"&gt;&lt;\/script&gt;\n\n    &lt;script&gt;\n        if ($(\"#registrationForm\").length &gt; 0) {\n            $(\"#registrationForm\").validate({\n\n                rules: {\n                    name: {\n                        required: true,\n                        maxlength: 50\n                    },\n                    email: {\n                        required: true,\n                        maxlength: 50,\n                        email: true,\n                    },\n                    password: {\n                        required: true,\n                        minlength: 5,\n                        maxlength: 20,\n                    },\n                    confirm_password: {\n                        required: true,\n                        equalTo: \"#password\",\n                    },\n                    phone: {\n                        required: true,\n                        digits: true,\n                        minlength: 10,\n                        maxlength: 12,\n                    },\n                    address: {\n                        required: true,\n                        minlength: 10,\n                        maxlength: 200,\n                    },\n                },\n                messages: {\n                    name: {\n                        required: \"Please enter your name\",\n                        maxlength: \"Name length should be 50 characters long.\"\n                    },\n                    email: {\n                        required: \"Please enter your email\",\n                        maxlength: \"Email length should be 50 characters long.\",\n                        email: \"Please enter a valid email\",\n                    },\n                    password: {\n                        required: \"Please enter your password\",\n                        minlength: \"Password must be greater than 5 chars\",\n                        maxlength: \"Password must not be greater than 20 chars\",\n                    },\n                    confirm_password: {\n                        required: \"Please re-enter your password\",\n                        equalTo: \"Password not confirmed\",\n                    },\n                    phone: {\n                        required: \"Please enter contact number\",\n                        minlength: \"The contact number should be 10 digits\",\n                        digits: \"Please enter only numbers\",\n                        maxlength: \"The contact number should be 12 digits\",\n                    },\n                    address: {\n                        required: \"Please enter your address\",\n                        minlength: \"Address must be greater than 10 chars\",\n                        maxlength: \"Address must not be greater than 200 chars\",\n                    },\n                },\n                submitHandler: function(form) {\n                    $('.response-message').removeClass('d-none');\n                    $('#submit-btn').html('Sending..');\n                    $.ajax({\n                        url: \"&lt;?php echo base_url('ajax-store') ?&gt;\",\n                        type: \"POST\",\n                        data: $('#registrationForm').serialize(),\n                        dataType: \"json\",\n                        success: function(response) {\n                            $('#submit-btn').html('Submit');\n                            $('.response-message').html(response?.message);\n                            response?.status === 'success' &amp;&amp; $('.response-message').addClass('text-success') || $('.response-message').addClass('text-danger');\n                            $('.response-message').show();\n                            $('.response-message').removeClass('d-none');\n\n                            document.getElementById(\"registrationForm\").reset();\n                            setTimeout(function() {\n                                $('.response-message').hide();\n                            }, 5000);\n                        }\n                    });\n                }\n            })\n        }\n    &lt;\/script&gt;\n\n&lt;\/body&gt;\n\n&lt;\/html&gt;<\/code><\/pre>\n\n\n\n<p>In the above code, I have added a very basic form. At the bottom, I&#8217;ve added jQuery to handle the form request. Also, the validation is there for the specified input fields. For the validation, I used the jQuery Validator plugin. This is used here to handle the validation with the form submit action. You can create a separate js file for this and you can add the script part in that. Then you can include that file inside this view file. That&#8217;s it in the above snippet.<\/p>\n\n\n\n<p>Now, let&#8217;s come to the functionality part where we&#8217;ll handle the form request. Also, we will save the form data in our table through the model. Hence, let&#8217;s do that.<\/p>\n\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/programmingfields.com\/generate-fake-data-in-codeigniter-4-using-seeder-and-faker\/\" target=\"_blank\" rel=\"noreferrer noopener\">Generate Fake Data in CodeIgniter 4 Using Seeder and Faker<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_a_Controller_For_Ajax_Form_Handling_in_CodeIgniter_4\"><\/span><strong>Create a Controller For Ajax Form Handling in CodeIgniter 4<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Come back to the terminal, and create a controller using the spark command.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">php spark make:controller AjaxController<\/code><\/pre>\n\n\n\n<p>After creating the controller, let&#8217;s put the below snippet inside it.<\/p>\n\n\n\n<pre title=\"AjaxController.php\" class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">&lt;?php\n\nnamespace App\\Controllers;\n\nuse App\\Controllers\\BaseController;\nuse App\\Models\\Ajaxform;\n\nclass AjaxController extends BaseController\n{\n\t\/**\n\t * Constructor\n\t *\/\n\tpublic function __construct()\n\t{\n\t\thelper(['form', 'url']);\n\t\t$this-&gt;ajaxForm = new Ajaxform();\n\t}\n\n\t\/**\n\t * Show Ajax Form\n\t * @param NA\n\t * @return view\n\t *\/\n\tpublic function index()\n\t{\n\t\treturn view('ajax-form');\n\t}\n\n\t\/**\n\t * Ajax Form Store Data\n\t * @param NA\n\t * @return response\n\t *\/\n\tpublic function store()\n\t{\n\t\t$data = [\n\t\t\t'name' =&gt; $this-&gt;request-&gt;getVar('name'),\n\t\t\t'email' =&gt; $this-&gt;request-&gt;getVar('email'),\n\t\t\t'password' =&gt; $this-&gt;request-&gt;getVar('password'),\n\t\t\t'phone' =&gt; $this-&gt;request-&gt;getVar('phone'),\n\t\t\t'address' =&gt; $this-&gt;request-&gt;getVar('address'),\n\t\t];\n\n\t\t$result = $this-&gt;ajaxForm-&gt;save($data);\n\t\tif ($result) {\n\t\t\treturn $this-&gt;response-&gt;setJSON(['status' =&gt; 'success', 'message' =&gt; 'User registered successfully']);\n\t\t}\n\t\treturn $this-&gt;response-&gt;setJSON(['status' =&gt; 'failed', 'message' =&gt; 'Failed to register']);\n\t}\n}\n<\/code><\/pre>\n\n\n\n<p>Let me explain the above code before moving to the next step.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>At the top, I have included the Model (Ajaxform).<\/li>\n\n\n\n<li>Then we have the constructor. In the constructor function, I have included the CodeIgniter helper functions. Which are required for handling form data. Also, I have created the object of the model.<\/li>\n\n\n\n<li>Now, coming to the <strong>index() function<\/strong>. In this function, I have loaded the view in which we already created a baisc form.<\/li>\n\n\n\n<li>Lastly, we have the <strong>store() function<\/strong> that handles the form data and insert operation through the model object.<\/li>\n<\/ul>\n\n\n\n<p>That&#8217;s it for the functionality we have. These functions needed a route to be run on the browser. So, let&#8217;s add the routes.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_Routes_in_CodeIgniter_4\"><\/span><strong>Create Routes in CodeIgniter 4<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>You can find the Routes.php under the <strong>app\/Config <\/strong>directory of the project. Now, add the below routes.<\/p>\n\n\n\n<pre title=\"Routes.php\" class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$routes-&gt;get('ajax-form', 'AjaxController::index');\n$routes-&gt;post('ajax-store', 'AjaxController::store');<\/code><\/pre>\n\n\n\n<p>Now, you are ready to go for the result.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Check_Results_of_CodeIgniter_AJAX_Form_Handling\"><\/span><strong>Check Results of CodeIgniter AJAX Form Handling<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Run the CodeIgniter 4 project using the spark command.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">php spark serve<\/code><\/pre>\n\n\n\n<p>Now, come to the browser, hit the URL and you will have the below result.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"671\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-04-09-06-33.png?resize=1024%2C671&#038;ssl=1\" alt=\"CodeIgniter 4 Ajax Form Handling Result\" class=\"wp-image-7315\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-04-09-06-33.png?resize=1024%2C671&amp;ssl=1 1024w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-04-09-06-33.png?resize=300%2C197&amp;ssl=1 300w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-04-09-06-33.png?resize=768%2C503&amp;ssl=1 768w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-04-09-06-33.png?w=1038&amp;ssl=1 1038w\" sizes=\"auto, (max-width: 1000px) 100vw, 1000px\" \/><figcaption class=\"wp-element-caption\"><strong>CodeIgniter 4 Ajax Form Handling Result<\/strong><\/figcaption><\/figure>\n<\/div>\n\n\n<p>If you will try to submit the form without filling up any fields then you will get validation errors.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1002\" height=\"705\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-04-09-06-50-1.png?resize=1002%2C705&#038;ssl=1\" alt=\"Form Validation Result Using jQuery Validator\" class=\"wp-image-7316\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-04-09-06-50-1.png?w=1002&amp;ssl=1 1002w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-04-09-06-50-1.png?resize=300%2C211&amp;ssl=1 300w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-04-09-06-50-1.png?resize=768%2C540&amp;ssl=1 768w\" sizes=\"auto, (max-width: 1000px) 100vw, 1000px\" \/><figcaption class=\"wp-element-caption\"><strong>Form Validation Result Using jQuery Validator<\/strong><\/figcaption><\/figure>\n<\/div>\n\n\n<p>Now, try to fill up the required fields and re-submit the form. As a result, you will get the success response as shown below. If the result is an error then the message will be displayed in red.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"970\" height=\"690\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-06-08-52-55.png?resize=970%2C690&#038;ssl=1\" alt=\"Codeigniter 4 Ajax Form - Success Response\" class=\"wp-image-7319\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-06-08-52-55.png?w=970&amp;ssl=1 970w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-06-08-52-55.png?resize=300%2C213&amp;ssl=1 300w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Screenshot-from-2021-12-06-08-52-55.png?resize=768%2C546&amp;ssl=1 768w\" sizes=\"auto, (max-width: 970px) 100vw, 970px\" \/><figcaption class=\"wp-element-caption\"><strong>Codeigniter 4 Ajax Form &#8211; Success Response<\/strong><\/figcaption><\/figure>\n<\/div>\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span><strong>Conclusion<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>We used Ajax in CodeIgniter 4 for the form handling. The form is able to submit without refreshing the page. Also, we added the jQuery validation for the form. For submitting the form, we haven&#8217;t created any submit events additionally. Instead, we used the submit handler of the jQuery validator. I hope this will make sense for you.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Ajax provides a technique to handle the form request without reloading the page. You can use Ajax in CodeIgniter 4 for handling form data. This will allow you to validate and submit your form without refreshing it. This is used at the client-side to handle the client request in the browser. If you are working [&hellip;]<\/p>\n","protected":false},"author":5,"featured_media":7321,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_genesis_hide_title":false,"_genesis_hide_breadcrumbs":false,"_genesis_hide_singular_image":false,"_genesis_hide_footer_widgets":false,"_genesis_custom_body_class":"","_genesis_custom_post_class":"","_genesis_layout":"","jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[12,1977,13],"tags":[1879,2223,2225,2066,2224,2226],"yst_prominent_words":[20,1286],"class_list":{"0":"post-7282","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-ajax-tutorial","8":"category-codeigniter-4","9":"category-jquery","10":"tag-ajax-form-handling","11":"tag-codeigniter-4-ajax-request","12":"tag-codeigniter-4-form-handling-using-ajax","13":"tag-codeigniter-4-form-validation","14":"tag-form-handling-using-ajax-in-codeigniter","15":"tag-form-request-handling-in-codeigniter","16":"entry"},"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/12\/Ajax-Form-Handling.png?fit=2240%2C1260&ssl=1","jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/posts\/7282","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/comments?post=7282"}],"version-history":[{"count":2,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/posts\/7282\/revisions"}],"predecessor-version":[{"id":8935,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/posts\/7282\/revisions\/8935"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/media\/7321"}],"wp:attachment":[{"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/media?parent=7282"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/categories?post=7282"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/tags?post=7282"},{"taxonomy":"yst_prominent_words","embeddable":true,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/yst_prominent_words?post=7282"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}