Datatable plugin is one of the popular JavaScript plugins. It displays the data in the table style. It comes with pagination, instant search, and column sorting out of the box.
However, in the user’s view, they want to be able to add, edit, or delete the data from the Datatable without leaving the current page. We can do that by using Ajax and the Bootstrap modal.
In this post, I will share with you how to add data from Datatable plugin using Bootstrap modal in CodeIgniter.
Integrate DataTable plugin to your view page
First thing, we need to integrate the DataTable plugin to our view page in CodeIgniter. You can follow my post here for instruction.
After integrating the DataTable plugin to your view page, your view page should display the data in the table view as below.
Add a New Data button
Next, we will add a New Data button. In your view page, add the code below above your table HTML tag.
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- Add New Data button -->
<button class="btn btn-primary mb-3" data-toggle="modal" data-target="#add_new_modal">Add New Data</button>
<!-- Render data in datatable plugin -->
<table id="rep_news" class="table table-striped table-bordered table-hover" style="width:100%">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Slug</th>
<th>Text</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Id</th>
<th>Title</th>
<th>Slug</th>
<th>Text</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
You will see the new button below. Notice that we add the Bootstrap classes as well as activate a Bootstrap modal via data attributes. You also can activate the Bootstrap modal via JavaScript. It is your choice.
The data attributes I add are data-toggle and data-target.
Add the Bootstrap modal on the view page
Next, we will add the Bootstrap modal HTML tag in the view page below our table tag. The code is below.
<div id="add_new_modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add News item</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<form method="post" id="insert_form">
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" class="form-control" placeholder="Enter title" />
</div>
<div class="form-group">
<label for="slug">Slug</label>
<input type="text" name="slug" id="slug" class="form-control" placeholder="Enter slug" />
</div>
<div class="form-group">
<label for="text">Text</label>
<input type="text" name="text" id="text" class="form-control" placeholder="Enter text" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="insert" id="insert" value="Add" class="btn btn-success" />
</div>
</form>
</div> <!-- .modal-body -->
</div> <!-- .modal-content -->
</div> <!-- .modal-dialog -->
</div> <!-- .modal -->
Notice that, I add the Id which is add_new_modal as same as the data-target attribute from the “Add New Data” button. This way, when we click on the button, the modal will popup.
But wait, we need to add the Bootstrap scripts at the footer in order to use the Bootstrap modal script.
Add Bootstrap script at the footer
Next, you will add the Bootstrap script at the footer template. You can get the Bootstrap script from here. The Bootstrap script needs a jQuery library as a dependency. However, in this post, we already use the Datatable plugin which needs the jQuery library as the dependency as well. Meaning, you don’t need to add the jQuery library twice.
Below is how the script look like at the footer template.
<!-- jQuery library -->
<script src="https://code.jquery.com/jquery-3.5.1.js" type="text/javascript"></script>
<!-- DataTable script -->
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js" type="text/javascript"></script>
<!-- Bootstrap script -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$('#rep_news').DataTable({
data: <?php echo json_encode($news) ?>,
columns: [{
"data": "id"
},
{
"data": "title"
},
{
"data": "slug"
},
{
"data": "text"
}
]
});
});
</script>
</body>
</html>
Bootstrap modal
Now, when you click on the New New Data button, you will see the modal window popup below.
Call Ajax for inserting new data
Next, we will add the ajax call at the footer template. The code is below.
<script>
$(document).ready(function() {
/**
* DataTable initialization
*/
$('#rep_news').DataTable({
data: <?php echo json_encode($news) ?>,
columns: [{
"data": "id"
},
{
"data": "title"
},
{
"data": "slug"
},
{
"data": "text"
}
]
});
/**
* Add new data via ajax
*/
$('#insert_form').on("submit", function(event) {
event.preventDefault();
// # form validation
// Optional, you can use the jQuery validation plugin (https://applerinquest.com/how-to-validate-a-form-with-jquery-validation-plugin/)
// if you don't want to do the form validation manually.
// For the warning message, you can use the Alert message from Bootstrap if you like. I use alert() because I want to keep the post short.
// https://getbootstrap.com/docs/4.0/components/alerts/
var $title = $('#title');
var $slug = $('#slug');
var $text = $('#text');
if ($title.val() == "") {
alert("Title is required");
$title.focus();
} else if ($slug.val() == '') {
alert("Slug is required");
$slug.focus();
} else if ($text.val() == '') {
alert("Text is required");
$text.focus();
} else {
$.ajax({
url: "<?php echo base_url('index.php/news/add_news_item') ?>",
method: "POST",
data: $('#insert_form').serialize(),
dataType: "JSON", // you must set dataType as JSON while sending the Ajax request
beforeSend: function() {
$('#insert').val("Adding");
},
success: function(response) {
// # get the response from our controller
// console.log(response);
// console.log(response.ins_status);
// console.log(response.data);
if (response.ins_status) {
// reset the form
$('#insert_form')[0].reset();
$('#insert').val("Add");
// hide the Bootstrap modal
$('#add_new_modal').modal('hide');
// refresh the Datatable plugin
$('#rep_news').dataTable().fnDestroy();
$('#rep_news').DataTable({
data: response.data,
columns: [{
"data": "id"
},
{
"data": "title"
},
{
"data": "slug"
},
{
"data": "text"
}
]
});
// success message
alert('success');
} else {
alert('data is not inserted. you must check the insert script in your model.');
}
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
});
}); // document ready ends
</script>
For the code above, when the form is submitted, we will do the form validation with JavaScript and show the warning message via an alert function. Optional, you can use the jQuery validation plugin for the form validation on the frontend as well.
Once the form validation rules are passed, we will use Ajax to call the add_news_item controller which we don’t create it yet. We are going to add it next.
Add “add_news_item” method in the controller
We will create the “add_news_item” method in our controller. So in our ajax, we can call it.
Open your controller, in my case, News controller and add code below.
<?php
class News extends CI_Controller
{
...
/**
* Insert new data from Bootstrap modal
*/
public function add_news_item()
{
$ins = $this->news_model->set_news();
$news = $this->news_model->get_news();
// # Return our data back to ajax with Json format (json_encode)
// you must use "echo" for returning the result you want.
echo json_encode(
// using the array for returning data
array(
'ins_status' => $ins,
'data' => $news
)
);
}
...
}
In the add_news_item method, we will insert a news item and query all news data for refreshing our data in the table.
Next, we will create the set_news method in our model. So we can insert the new data into your database.
Add “set_news” method in the model
Open your model, in my case, it is a news model. Then add the code below.
<?php
class News_model extends CI_Model
{
...
public function set_news()
{
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
...
}
Now, when you add the new data into the modal, the data should insert into the database.
From the image above, you will see I add News#5 item on the adding form then I clicked on Add button.
The Ajax is called and the button text changes from Add to Adding.
Once the insertion is done, we will show the Success message. Then the form will be reset and hide from the screen. Lastly, the data in the table will be refreshed by ajax without refresh the whole page.
When you search News#5 in the search box, you will see this new data.
That’s it.
Troubleshoot
- 404 file not found
- If you call the ajax while inserts new data and get the 404 response, it might be your route is incorrect. Check your route again. In my case, I need to include “index.php” in my route as I set in application/config/config.php.
- 500 internal server error
- If you call the ajax while inserts new data and get the 500 response, it might be your insert script in the model is incorrect.
Conclusion
In this post, we learn how to add new data from the Bootstrap modal. We learn how to add the new data via Ajax in CodeIgniter. Also, we learn how to refresh the data in the Datatable in Ajax. I hope this post is useful.