How To Insert Records Using Ajax jQuery In CodeIgniter

Create a form in your view file to collect the data you want to insert into the database.

Create a function in your controller file that will handle the Ajax request. This function should retrieve the data from the POST request and insert it into the database.

Create a JavaScript file to send the data to the controller using Ajax. This file should listen for the submit event on the form and then use jQuery's Ajax function to send the data to the controller.

Here is a more detailed breakdown of the steps,

Step 1

Create a form in your view file

<!-- create a form to collect data -->
<form id="myForm" method="post">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name">
  <label for="email">Email:</label>
  <input type="text" id="email" name="email">
  <button type="submit" id="submit">Submit</button>
</form>

Step 2

Create a controller function to handle the Ajax request.

public function insert_data() {
    // Retrieve data from the POST request
    $name = $this - > input - > post('name');
    $email = $this - > input - > post('email');
    // Insert data into the database
    $this - > db - > insert('users', array('name' => $name, 'email' => $email));
    // Send a response back to the JavaScript file
    if ($this - > db - > affectedRows() > 0) {
        echo 'Data inserted successfully';
    } else {
        echo 'Data Insert failed';
    }
}

Step 3

Create a MySQL database table 'users'.

CREATE TABLE `users` (
    `id` int(11) NOT NULL,
    `name` varchar(40) NOT NULL,
    `email` varchar(60) NOT NULL,
    `created_at` datetime NOT NULL DEFAULT current_timestamp()
)

Step 4

Create a JavaScript file to send the data to the controller using Ajax.

// Listen for the submit event on the form
$('#myForm').submit(function(event) {
    event.preventDefault();
    // Retrieve the data from the form
    var name = $('#name').val();
    var email = $('#email').val();
    // Send the data to the controller using Ajax
    $.ajax({
        url: '<?php echo base_url() ?>index.php/users_controller/insert_data',
        method: 'post',
        data: {
            name: name,
            email: email
        },
        success: function(response) {
            alert(response);
        }
    });
});

That's it! With these four simple steps, you can insert data into your database using Ajax jQuery in CodeIgniter.

Next Recommended Reading Codeigniter Login With AJAX