CodeIgniter 4 Ajax Form Submit Validation Example Tutorial

Apr 20, 2022 . Admin



Hi Dev,

Today, ajax form validation in Codeigniter 4 is our main topic. This post will give you a simple example of form validation with Ajax in Codeigniter 4. I’m going to show you about Codeigniter 4 ajax form validation example. if you want to see an example of Codeigniter 4 ajax form validation then you are in the right place. you will do the following things for form validation in Codeigniter 4 using ajax.

Right here, CodeIgniter four tutorial, we are able to create a contact form and publish touch form the use of Ajax and validate the contact shape earlier than sending the shape records to the server in CodeIgniter 4. And this touch form will send statistics to the server without clean the whole page and additionally, the shape will insert the statistics into the database in CodeIgniter 4 framework.

Step 1: Install Codeigniter 4

This is optional; however, if you have not created the codeigniter app, then you may go ahead and execute the below command:

composer create-project codeigniter4/appstarter ci-news
Step 2: Basic Configurations

Next, we will set some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';
Step 3: Create Database With Table

On this step, we want to create a database call demo, so allow’s open your PHPMyAdmin and create the database with the call demo. After efficaciously create a database, you could use the below square question for creating a desk to your database.

CREATE TABLE contacts (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(100) NOT NULL COMMENT 'Name',
    email varchar(255) NOT NULL COMMENT 'Email Address',
    message varchar(250) NOT NULL COMMENT 'Message',
    created_at varchar(20) NOT NULL COMMENT 'Created date',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='demo table' AUTO_INCREMENT=1;
Step 4: Setup Database Credentials

on this step, we want to connect our challenge to the database. we need to go app/Config/Database.php and open database. personal home page file in the textual content editor. After opening the document in a textual content editor, We want to set up database credentials in this file like underneath.

app/Config/Database.php
public $default = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'demo',
    '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 Model

So visit app/models/ and create here one version. and you need to create one model name ContactModel.

<?php
namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
 
class ContactModel extends Model
{
    protected $table = 'contacts';
 
    protected $allowedFields = ['name', 'email', 'message'];
}
Step 6: Create Controller

Now go to app/Controllers and create a controller call Contact.php. in this controller, we are able to create a few method/feature. we are able to build a number of the strategies like :

app/Controllers/Contact.php
<?php 
namespace App\Controllers; 
use CodeIgniter\Controller;
use App\Models\ContactModel;
 
class Contact extends Controller
{

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {    
        return view('contact');
    }
 
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {  
        helper(['form', 'url']);
         
        $db      = \Config\Database::connect();
        $builder = $db->table('contacts');
 
        $data = [
 
            'name' => $this->request->getVar('name'),
            'email'  => $this->request->getVar('email'),
            'message'  => $this->request->getVar('message')
            ];
 
            $save = $builder->insert($data);
 
        $data = [
            'success' => true,
            'data' => $save,
            'msg' => "Thanks for contact us. We get back to you"
        ];
 
        return $this->response->setJSON($data);
    }
}
Step 7: Create Views

Now, in this step we need to create Contact.php, go to application/views/ folder and create contact.php file. and update the following HTML into your files:

application/views/contact.php
<!DOCTYPE html>
<html>
<head>
    <title>Codeigniter 4 ajax insert form with validation - Mywebtuts.com</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">
    <br>
    <?= \Config\Services::validation()->listErrors(); ?>
 
    <span class="d-none alert alert-success mb-3" id="res_message"></span>
 
    <div class="row">
        <div class="col-md-9">
            <form action="javascript:void(0)" name="ajax_form" id="ajax_form" method="post" accept-charset="utf-8">
 
            <div class="form-group">
                <label for="formGroupExampleInput">Name</label>
                <input type="text" name="name" class="form-control" id="formGroupExampleInput" placeholder="Please enter name">
            </div> 
 
            <div class="form-group">
                <label for="email">Email Id</label>
                <input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id">
            </div>   
 
            <div class="form-group">
                <label for="message">Message</label>
                <textarea name="message" class="form-control"></textarea>
            </div>
 
            <div class="form-group">
                <button type="submit" id="send_form" class="btn btn-success">Submit</button>
            </div>
        </form>
      </div>
    </div>
</div>
<script>

    /*------------------------------------------
    --------------------------------------------
    Ajax Form
    --------------------------------------------
    --------------------------------------------*/
    if ($("#ajax_form").length > 0) {
        $("#ajax_form").validate({
      
            rules: {
                name: {
                    required: true,
                },
          
                email: {
                    required: true,
                    maxlength: 50,
                    email: true,
                }, 
         
                message: {
                    required: true,
                },   
            },
            messages: {
                
                name: {
                    required: "Please enter name",
                },
                email: {
                    required: "Please enter valid email",
                    email: "Please enter valid email",
                    maxlength: "The email name should less than or equal to 50 characters",
                },      
                message: {
                    required: "Please enter message",
                },
                 
            },
            submitHandler: function(form) {
                $('#send_form').html('Sending..');
                $.ajax({
                    url: "<?php echo base_url('contact/create') ?>",
                    type: "POST",
                    data: $('#ajax_form').serialize(),
                    dataType: "json",
                    success: function( response ) {
                        console.log(response);
                        console.log(response.success);
                        $('#send_form').html('Submit');
                        $('#res_message').html(response.msg);
                        $('#res_message').show();
                        $('#res_message').removeClass('d-none');
             
                        document.getElementById("ajax_form").reset(); 
                        setTimeout(function(){
                            $('#res_message').hide();
                            $('#res_message').html('');
                        },10000);
                    }
                });
            }
        })
    }
</script>
</body>
</html>

This below line display error messages on your web page:

<?= \Config\Services::validation()->listErrors(); ?>

You need to add jQuery validation library given below in contact form:

<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>

When you include the jQuery validation library on contact us web page. After this, you will also have to write validation rules of jQuery on the contact page. Also, you need to write ajax form submit code. Which are given below:

<script>
    if ($("#ajax_form").length > 0) {
        $("#ajax_form").validate({
      
            rules: {
                name: {
                required: true,
            },
      
            email: {
                required: true,
                maxlength: 50,
                email: true,
            }, 
     
            message: {
                required: true,
            },   
        },
        messages: {
            
            name: {
                required: "Please enter name",
            },
            email: {
                required: "Please enter valid email",
                email: "Please enter valid email",
                maxlength: "The email name should less than or equal to 50 characters",
            },      
            message: {
                required: "Please enter message",
            },
             
        },
        submitHandler: function(form) {
            $('#send_form').html('Sending..');
            $.ajax({
                url: "<?php echo base_url('public/index.php/contact/create') ?>",
                type: "POST",
                data: $('#ajax_form').serialize(),
                dataType: "json",
                success: function( response ) {
                    console.log(response);
                    console.log(response.success);
                    $('#send_form').html('Submit');
                    $('#res_message').html(response.msg);
                    $('#res_message').show();
                    $('#res_message').removeClass('d-none');
         
                    document.getElementById("ajax_form").reset(); 
                    setTimeout(function(){
                        $('#res_message').hide();
                        $('#res_message').html('');
                    },10000);
                }
            });
        }
    })
}
</script>
Step 8 : Run Codeigniter App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Codeigniter app:

php spark serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8080/

It will help you...

#Codeigniter 4