How to insert data into the database using Ajax in CodeIgniter 3

Inserting data into the database is one of the common operations in any software application. Ajax stands for “Asynchronous JavaScript and XML“. By using Ajax, we can send data to the server without refreshing the webpage. In this tutorial, I am going to share with you how to insert data into the database using Ajax in CodeIgniter 3?

Ajax is not a programming language, it is just a client-side script that helps to communicate with the server. It increases the execution speed of any project because it doesn’t refresh the browser at the time sending data to the server.

Let me tell you how to insert data into the database using Ajax in CodeIgniter 3? In this tutorial, I will share code with the explanation that will help you to understand each process.

To understand this tutorial, you must have knowledge of CodeIgniter 3 because, in this tutorial, I will share only the data insertion process by Ajax.

insert data into the database
insert data into the database

Hindi Tutorials : Click here for Hindi tutorial

Video Tutorial: Click here for Video Tutorial

Insert data into the database using Ajax in CodeIgniter 3?

First, I have created a database named “ajax_test” and inside it, I have created a simple table named “person“. You can see the structure and code of that table below.

CREATE TABLE `person` (
 `name` varchar(255) NOT NULL,
 `message` varchar(255) NOT NULL,
 `age` int(11) NOT NULL,
Table Structure
Table Structure

Now, download CodeIgniter 3 folders from their official website. Click here to go to the official website.

After that, simply extract that ZIP folder and keep that folder in your PHP working environment. For example, if you are using XAMPP then put that folder inside htdocs folder and if you are using WAMP then put that folder in the www folder and so on.

Next, set up basic instruction of CodeIgniter 3 like set .htaccess file in the root folder and paste the below code in this file to remove index.php from the URL.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

Next, set the base URL according to your project path. Here, my project folder is ajax then I am setting a base URL like ‘http://localhost/ajax/’. To set the base URL to go to the application folder inside it go to the config folder and then open the config.php file and set your base URL.

After that set the database username, password, and database name in the database.php file. This file resides in the application >> config folder.

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'ajax_test',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE

Now create a View inside application >> views folder. In which, we will write HTML code that will display on web browsers. Here, I am creating a view file name with index.php.


<!DOCTYPE html>
        <title>Insert data into database by using Ajax in CodeIgniter 3</title>
        <link rel="stylesheet" type="text/css" href="">
        <link rel="stylesheet" href="">
        <div class="container">
            <!--button to open form modal-->
            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#createModal">
                Add Record
            <!--button to open form modal end-->

            <form id="createForm">
                <!-- Modal -->
                <div class="modal fade" id="createModal" aria-hidden="true">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="exampleModalLongTitle">Add Record</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">×</span>
                            <div class="modal-body">

                                <div class="form-group">
                                    <input type="text" class="form-control" placeholder="Name here" name="name">
                                <div class="form-group">
                                    <input type="text" class="form-control" placeholder="Message Here" name="message">
                                <div class="form-group">
                                    <input type="number" class="form-control" placeholder="Age Here" name="age">

                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary pull-left" data-dismiss="modal">Close</button>
                                <button type="submit" class="btn btn-primary">Save</button>

            <table id="example1" class="display table">


        <script type="text/javascript" src=""></script>
        <script type="text/javascript" src=""></script>
        <script src=""></script>
        <script src=""></script>

        <script type="text/javascript">
            //initializing datatable
            $(document).ready(function () {

            //submitting form
            $("#createForm").submit(function (event) {
                event.preventDefault(); //prevent the browser to execute default action. Here, it will prevent browser to be refresh
                    url: "<?php echo base_url('my_controller/create'); ?>", //backend url
                    data: $("#createForm").serialize(), //sending form data in a serialize way
                    type: "post",
                    async: false, //hold the next execution until the previous execution complete
                    dataType: 'json',
                    success: function (response) {

                        $('#createModal').modal('hide'); //hiding modal
                        $('#createForm')[0].reset(); //reset form
                        alert('Successfully inserted'); //displaying a successful message
                        $('#exampleTable').DataTable().ajax.reload(); //rereshing the datatable to add new data in datatable
                    error: function ()
                        alert("error"); //error occurs

In this view file, I have linked two CSS files. One is datatable CSS and another one is bootstrap CSS which will help to give a better look of our design.

After that, I have created a button inside body tag. When anyone click on this button then a modal appears on the web page. Modal code has been written just after the button code. In the modal, I have created three fields name, message, and age and then two button are created close and save.

After modal code, a simple table has been created. In this table, we will show data after getting from database in next tutorial.

Next, jQuery, Datatable, and bootstrap JavaScript files are linked and after that, datatable is initializing.

Next, form is submitting and different code executes and perform different actions.

  • event.preventDefault() prevents the default action of that form which means it prevents the browser to be refreshed.
  • The complete path of the backend has been given in the URL.
  • Next, the form data is assigning to the data name in the serialize way.
  • async: false holds the next execution of the process until the previous execution is complete.
  • Inside the success prototype, we are performing different operations.

Now, create a controller that will help you to interact with the view and modal. The controller receives a request from the view and sends that request to the modal. Modal execute that request in the database and send back a response to the controller and the controller returns the response to the views. I have created a controller inside the application >> controllers folder.



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

class MY_Controller extends CI_Controller {

    public function __construct() {
     * function helps to load a view page
    public function index() {
     * function helps to insert data into database
    public function create() {
        $name = $this->input->post('name');
        $message = $this->input->post('message');
        $age = $this->input->post('age');

        $data = array(
            'name' => $name,
            'message' => $message,
            'age' => $age,
        $insert = $this->ajax_model->createData($data);
        echo json_encode($insert);

In this controller, I have created a class name with MY_Controller which is also the file name. In this class, I have extends CI_Controller to inherit all features of the CodeIgniter default controller to this controller.

Inside this class, a constructor function is executing and getting all features of their parent class. Next, index() function loads the view page and then a create() function exists, in which, we will receive the form data which is sent by the Ajax and then an array is created with the variable and column name of the table. After that, model is loading by $this->load->model() function. After that, the model function is calling by the help of a modal name. The model receives this request and communicates with the database to perform a specific operation and then it will return a response to the controller and controller return that response to the view in the form of JSON.

Now, let’s see the model code. I have created a model inside the application >> models folder. The name of the model file is the same as the name of the model class.



class Ajax_model extends CI_Model {

    public function createData($data) {
        $query = $this->db->insert('person', $data);
        return $query;


An Ajax_model is created and it extends CI_Model to inherit all the features of the default CodeIgniter model. Inside it, a createData() function has been created and in this function, a parameter $data is passing. In this parameter, all data of the form data has been set from the controller and it will save to the database with the help of insert() function.

insert() function accepts two parameters. The first parameter is the table name and the second parameter is the data that is inserted into the database. The second parameter must be an array. After inserting the data into the database, it will return the response.

Conclusion and Final Words

Ajax is very helpful to send a request to the server without refreshing the browser. It increases the process of the project because it doesn’t refresh the browser that’s why it saves the time by preventing browser refresh.

In this tutorial, we learned how to insert data into the database by using Ajax in CodeIgniter 3? I hope this will be very helpful for all of you.

Leave a Reply

Your email address will not be published. Required fields are marked *

error: Content is protected !!