Ajax Form Submit In Codeigniter


In this tutorial, I will show you how to submit a form using ajax without page refresh in Codeigniter. We will simple coding of ajax form submit in Codeigniter.

When you click on submit button then it will automatically submit event of jquery. In submit event I write to code of ajax with post request and send all input text value as a parameter. you can also use same code on Controller & modal form submit because it will not refresh page.

So, in this tutorial we will create new table "users" and then we simple list out that column in view file. then we will write ajax request code and it will fire ajax post request from view file and save data in the database.

Step 1: Create Table

I created "users" table, so run bellow query:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `email_id` varchar(255) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=
Step 2: Create Route

we need to add one route for ajax search data and another for view. so open routes.php

application/config/routes.php

$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

$route['ajax-request'] = 'userController/ajaxRequest';
$route['ajax-requestPost']['post'] = 'userController/ajaxRequestPost';
Step 3: Create Controller

So, create new ItemController.php file in controllers folder and put bellow code:

application/controllers/userController.php

<?php


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


class userController extends CI_Controller {


   /**
    * Get All Data from this method.
    *
    * @return Response
   */
   public function __construct() {
      parent::__construct();
      $this->load->database();
   }


   /**
    * Get All Data from this method.
    *
    * @return Response
   */
   public function ajaxRequest()
   {
       $data['data'] = $this->db->get("users")->result();
       $this->load->view('userlist', $data);
   }


   /**
    * Get All Data from this method.
    *
    * @return Response
   */
   public function ajaxRequestPost()
   {
      $data = array(
            'name' => $this->input->post('name'),
            'email_id' => $this->input->post('email')
        );
      $this->db->insert('users', $data);


      echo 'Added successfully.';  
   }
}
?>
Step 4: Create View Page

we have to create view file, If you installed fresh codeigniter then we need to create userlist.php

application/views/userlist.php

<!DOCTYPE html>
<html>
<head>
    <title>Ajax Form Submit In Codeigniter - Php Coding Stuff</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h2>Ajax Form Submit In Codeigniter - Php Coding Stuff</h2>
        </div>
    </div>
</div>


<div class="row">
  <div class="col-lg-8">
    <strong>Name:</strong>
    <input type="text" name="name" class="form-control" placeholder="Name">
  </div>
  <div class="col-lg-8">
    <strong>Email Id:</strong>
    <textarea name="email" class="form-control" placeholder="Email Id"></textarea>
  </div>
  <div class="col-lg-8">
    <br/>
    <button type="submit" class="btn btn-success">Submit</button>
  </div>
</div>


<table class="table table-bordered" style="margin-top:20px">


  <thead>
      <tr>
          <th>Name</th>
          <th>Email</th>
      </tr>
  </thead>


  <tbody>
   <?php foreach ($data as $user) { ?>      
      <tr>
          <td><?php echo $user->name; ?></td>
          <td><?php echo $user->email_id; ?></td>
      </tr>
   <?php } ?>
  </tbody>


</table>
</div>


<script type="text/javascript">
    $('form').submit(function(e) {
        e.preventDefault();


       var name = $("input[name='name']").val();
       var email = $("textarea[name='email']").val();


        $.ajax({
           url: '/ajax-requestPost',
           type: 'POST',
           data: {name: name, email: email},
           error: function() {
              alert('Something is wrong');
           },
           success: function(data) {
                $("tbody").append("<tr><td>"+name+"</td><td>"+email+"</td></tr>");
                alert("Record added successfully");  
           }
        });


    });


</script>


</body>
</html>

so you can check your own.


I hope it can help you...

Leave a Reply

Your privacy will not be published. Required fields are marked *

We'll share your Website Only Trusted.!!

close