how to append data after ajax call in dataTable - json

I am using dataTable jquery plugin.My data comes from ajax. code shown below
I want to create table after ajax call. In my html file
$(document).ready(function(){
$(".report-table").DataTable({
"pagingType": "full_numbers"
});
});
In my javascript
$("#student_report_form_btn").on('click',function(){
$("#student_report_detail_list").empty();
if($("#student_report_form").valid())
{
$.ajax({
url:site + 'index.php/user_report',
type:"post",
dataType:"json",
data:sume data,
success:function(msg){
if(msg.user_report_detail !='')
{
//dddd(msg);return false;
student_report_table = '';
student_report_table += '<div class="table-responsive">';
student_report_table += '<table class="table table-bordered report-table" id="report-table">';
student_report_table +='<tr><th>Date</th><th>Intime</th><th>Outtime</th></tr>';
$.each(msg.user_report_detail,function(k,v){
student_report_table += '<tr><td>'+ v['date'] +'</td><td>'+ v['intime'] +'</td><td>'+ v['outtime'] +'</td></tr>';
});
student_report_table += '</table>';
student_report_table += '</div>';
$("#student_report_detail_list").append(student_report_table);
}else{
$("#student_report_detail_list").append("<div class='alert alert-danger'>" +
"<button type='button' class='close' data-dismiss='alert' aria-label='Close'> <span aria-hidden='true'>×</span></button>" +
"<strong>Sorry!</strong> There are not records for this user." +
"</div>");
setTimeout(function() { $('.alert').alert('close'); }, 2000);
}
}
});
}
});
The dataTable here does not work. Please help.

if your method to create the table works (there are far better possibilities to create a datatable) i think the only problem is you've to initialize your table
try the following
$("#student_report_form_btn").on('click',function()
{
$("#student_report_detail_list").empty();
if($("#student_report_form").valid())
{
$.ajax({
url:site + 'index.php/user_report',
type:"post",
dataType:"json",
data:sume data,
success:function(msg){
if(msg.user_report_detail !='')
{
//dddd(msg);return false;
student_report_table = '';
student_report_table += '<div class="table-responsive">';
student_report_table += '<table class="table table-bordered report-table" id="report-table">';
student_report_table +='<tr><th>Date</th><th>Intime</th><th>Outtime</th></tr>';
$.each(msg.user_report_detail,function(k,v){
student_report_table += '<tr><td>'+ v['date'] +'</td><td>'+ v['intime'] +'</td><td>'+ v['outtime'] +'</td></tr>';
});
student_report_table += '</table>';
student_report_table += '</div>';
$("#student_report_detail_list").append(student_report_table);
$("#student_report_detail_list .report-table").DataTable({
"pagingType": "full_numbers"
});
}else{
$("#student_report_detail_list").append("<div class='alert alert-danger'>" +
"<button type='button' class='close' data-dismiss='alert' aria-label='Close'> <span aria-hidden='true'>×</span></button>" +
"<strong>Sorry!</strong> There are not records for this user." +
"</div>");
setTimeout(function() { $('.alert').alert('close'); }, 2000);
}
}
});
}
});

Related

How to make pagination with pagination js use ajax

I'm trying to create a pagination using pagination js. I use the data using ajax and api. When I try to make it there is an error. How do I fix it?
Am I wrong to make the ajax, but if I don't use pagination js the data is visible in the table. I've tried various ways but I don't really understand using pagination js.
function s() {
var FilterObjDTO = []
console.log(FilterObjDTO);
var SortObjDTO = []
console.log(SortObjDTO);
var PagingObjDTO = { offset: 0, totalPerPage:4, paging: false }
console.log(PagingObjDTO);
var willSendToAPI = {
filter: FilterObjDTO, sort: SortObjDTO, paging: PagingObjDTO
}
console.log(willSendToAPI);
$('#DataTable').pagination({
dataSource: function (done) {
$.ajax({
type: 'GET',
url: origin + '/' + 'id-ID' + '/' + 'DataTable',
data: { input: JSON.stringify(willSendToAPI) },
success: function (data) {
console.log(data);
var html = '';
for (var i = 0; i < data.length; i++) {
html += '<table id="DataTable" style="width: 100%">';
html += '<colgroup>';
html += '<col span="1" style="width: 10%;">';
html += '<col span="1" style="width: 14%;">';
html += '<col span="1" style="width: 29%;">';
html += '<col span="1" style="width: 14%;">';
html += '<col span="1" style="width: 14%;">';
//html += '</colgroup>';
//html += '<tr class="table-border" style="background-color:#f4f5fa;">';
//html += '<th>Title</th>';
//html += '<th class="text-center">Type</th>';
//html += '<th class="text-center">Slug</th>';
//html += '<th class="text-center">PDF</th>';
//html += '<th class="text-center">Edit</th>';
html += '<tbody id="table">';
html += '<tr>';
html += '<td>' + data[i].fTitleID + '</td>';
html += '<td>';
html += '<p class="m-auto t-category">' + data[i].fType + '</p>';
html += '</td>';
html += '<td class="text-center">' + data[i].fSlug + '</td>';
html += '<td class="text-center"><a><i class="fas fa-file-download"></i></a></td>';
html += '<td class="text-center"> <button class="button-edit">edit</button></td>';
html += '</tr>';
html += '</tbody>';
html += '</table>';
}
$('#table').html(html);
}
});
pageSize: 5,
autoHidePrevious: true,
autoHideNext: true,
callback: function(data, pagination) {
// template method of yourself
var html = template(data);
dataContainer.html(html);
}
})
}

How to make dynamic HTML table data (created using jQuery) clickable?

I am new to these and have tried creating an HTML table dynamically using jQuery. The code is as below. It works fine.
How can I make the table data (value.id) clickable so that it redirects to a different page?
$(document).ready(function() {
var tableData = '';
$.each(xyz, function(key, value) {
tableData += '<tr>';
tableData += '<td>' + value.id + '</td>';
tableData += '<td>' + value.name + '</td>';
tableData += '</tr>';
});
$('#table').append(tableData);
//});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead></thead>
<tbody id="table"></tbody>
</table>
Like this
const xyz = [{
id: 1,
name: "one"
},
{
id: 2,
name: "two"
}
]
$(function() {
const tableData = xyz.map(item => (`<tr><td class="id">${item.id}</td>
<td>${item.name}</td></tr>`));
$('#table').append(tableData.join(""));
$('#table').on("click", ".id", function() {
const id = this.textContent
console.log(id);
// location = "https://google.com/search?q="+id;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead></thead>
<tbody id="table"></tbody>
</table>
You can enclose your tile content with a "a" tag
`tableData += '<tr>';
tableData += '<td><a href="/you-url/' +value.id+ '">' +
value.id + '<'/a></td>';
tableData += '<td>' +
value.name + '</td>';
tableData += '</tr>';`
I prefer to give the clickable elements a class to reference:
I also have some CSS that sets the cursor to a pointer.
$(document).ready(function () {
var tableData = '';
$.each(xyz, function (key, value) {
tableData += '<tr>';
tableData += '<td class="link">' +
value.id + '</td>';
tableData += '<td>' +
value.name + '</td>';
tableData += '</tr>';
});
$('#table').append(tableData);
//});
});
$(document).on("click","#table .link",function(){
console.log($(this).html());
});
.link{cursor:pointer;}

How do I get the form data in Codeigniter controller using ajax?

http://zivite.com/salary/
Hi, Guys please visit the link above mentioned.
Whenever choosing the designation from the dropdown, it will be listed all the data associated with that particular designation.
In the loop data, I have added form around the tr and submit button as well as added some additional fields like attendance, loan, rate etc. Whenever hit the submit button for a particular person. it should be stored in my database table which called the salary table.
Now my problem is not getting the data inside the model when we hit the submit button,
If you inspect it you can see array is creating there but no data from the submitted form
see this image link below
https://ibb.co/h11SgMV
// view
<?php include "template/header.php"; ?><!-- Start Page content -->
<div class="content">
<div class="container-fluid">
<div class="card-box">
<form action="%3C?php%20echo%20base_url('con_employee/employeeSearch');%20?%3E" class="form-inline" method="post">
<div class="form-group" style="padding-right:10px; width:100%;">
<select class="custom-select" id="empDesignation" name="empDesignation">
<option selected>
Designation
</option><?php foreach($categories as $category){ ?>
<option value="<?php echo $category['cat_id']; ?>">
<?php echo $category['cat_name']; ?>
</option><?php } ?>
</select>
</div>
</form><br>
<div class="row">
<table class="table table-hover table-centered m-0 table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Designation</th>
<th>Account Number</th>
<th>Attendance</th>
<th>Rate</th>
<th>Loan</th>
<th>Action</th>
</tr>
</thead>
<tbody id="salaryData"></tbody>
</table>
</div>
</div>
</div><!-- container -->
</div><!-- content -->
<!-- end row -->
<script>
$(function() {
$('#empDesignation').change(function() {
var user_designation = $(this).val();
if (user_designation == '') {
$('#empName').prop('disabled', true);
} else {
$('#empName').prop('disabled', false);
$.ajax({
url: "<?php echo site_url(); ?>con_salary/add_salary_for_employee",
type: "POST",
data: {
'user_designation': user_designation
},
dataType: 'json',
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
html += '<tr>' +
'<form class="" id="myform">' +
'<td>' + data[i].emp_name + ' <\/td>' +
'<td>' + data[i].cat_name + '<\/td>' +
'<td>' + data[i].emp_account_number + '<\/td>' +
'<td>' +
'<input type="text" class="form-control" name="attendance" placeholder="Attendance" required>' +
'<\/td>' +
'<td>1<\/td>' +
'<td>' +
'<input type="text" class="form-control" name="loan" placeholder="Loan" required>' +
'<\/td>' +
'<td>' +
'<a href="javascript:;" class="btn btn-primary item-edit" id="btnSave">Submit<\/a>' +
'<\/td>' +
'<\/form>' +
'<\/tr>';
}
$('#salaryData').html(html);
// $('#salaryData').html(data);
},
error: function() {
alert('No Data');
}
});
}
});
});
//insert data to salary table
$('#salaryData').on('click', '.item-edit', function() {
$('#myform').attr('action', '<?php echo base_url() ?>con_salary/addSalary');
var url = $('#myform').attr('action');
var data = $('#myform').serialize();
var attendance = $('input[name=attendance]');
var loan = $('input[name=loan]');
$.ajax({
type: 'ajax',
method: 'POST',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response) {
},
error: function() {
}
});
});
</script> <?php include "template/footer.php"; ?>
// controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Con_salary extends CI_Controller
{
public function __construct(){
parent:: __construct();
$this->load->model('queries_salary');
}
public function index()
{ $data['categories'] = $this->queries_salary->fetchCategory();
$this->load->view('employee_salary_view',$data);
}
public function add_salary_for_employee()
{
$designation_id=$this->input->post('user_designation');
$users = $this->queries_salary->fetchEmployeeforsalary($designation_id);
echo json_encode($users);
}
public function addSalary()
{
$result = $this->queries_salary->addSalary();
// $msg['success']=false;
// $msg['type']='add';
// if($result){
// $msg['success']=true;
// }
// echo json_encode($msg);
}
//end
}
?>
// model
<?php
class Queries_salary extends CI_Model
{
public function fetchCategory()
{
$query= $this->db->get('category');
return $query->result_array();
}
public function fetchEmployeeforsalary($designation_id)
{
$this->db->where('emp_designation_id',$designation_id);
$this->db->join('category','employee.emp_designation_id = category.cat_id');
$query=$this->db->get('employee');
if($query->num_rows()>0){
return $query->result();
}
else{
return false;
}
// $this->db->where('emp_designation_id',$designation_id);
// $query=$this->db->get('employee');
}
public function addSalary()
{
$field = array(
'salary_attendance'=>$this->input->post('attendance'),
'salary_loan'=>$this->input->post('loan')
);
print_r($field);
exit();
// $this->db->insert('salary',$field );
// if($this->db->affected_rows()>0)
// {
// return true;
// }
// else{
// return false;
// }
}
//end
}?>
A form is not allowed to be a child of a table, tbody or tr HTML elements.
If attempting to put one there will tend to cause the browser to move the form to it appears after the table.So in your case form results an empty data.
Here i adjusted code your code little bit and will work for you.
for (i = 0; i < data.length; i++) {
html += '<tr class="user_data" >' +
'<td>' + data[i].emp_name + ' <\/td>' +
'<td>' + data[i].cat_name + '<\/td>' +
'<td>' + data[i].emp_account_number + '<\/td>' +
'<td>' +
'<input type="text" class="form-control attendance" name="attendance" placeholder="Attendance" required>' +
'<\/td>' +
'<td>1<\/td>' +
'<td>' +
'<input type="text" class="form-control loan" name="loan" placeholder="Loan" required>' +
'<\/td>' +
'<td>' +
'<a href="javascript:;" class="btn btn-primary item-edit" id="btnSave">Submit<\/a>' +
'<\/td>' +
'<\/tr>';
}
Bottom side script
$('#salaryData').on('click', '.item-edit', function() {
var url = '<?php echo base_url() ?>con_salary/add_salary_for_employee';
var current_row = $(this).closest('.user_data');
var data = { attendance: current_row.find('.attendance').val(), loan: current_row.find('.loan').val() };
$.ajax({
type: 'ajax',
method: 'POST',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response) {
},
error: function() {
}
});
});
One important note is that if you are using single form and using same type of input with same name use it as Array.
Eg : name="loan[]"

How to clear previous search result shown by ajax success?

I wanted to clear all the search result shown by ajax search like when the user type for next query it will update it.
$(document).ready(function(){
var text;
$("#button").on('click',function (e) {
e.preventDefault();
var q=$("#q").val();
$.ajax({
url: "/search",
data: {q:q},
type: "GET",
dataType : "json",
success: function(result) {
var event_data = '';
for (var i = 0; i < result.length; i++) {
event_data += '<tr>';
event_data += '<td>' + '<img src=' +result[i]['video']['thumbnail_src']+ '></img>' +'</td>';
event_data += '<td>' +result[i]['video']['title']+'</td>';
event_data += '<td>' +result[i]['video']['duration']+ '</td>';
event_data += '<td>' + '<a href' +result[i]['video']['url']+ '>'+ "Download" +'</a>' +'</td>';
event_data += '</tr>';
} $("#list_table_json").append(event_data);
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
},
always: function( xhr, status ) {
alert( "The request is complete!" );
}
});
});
});
This is my html file for table where i was appending result from ajax success, can you guys let me know another technique for this. I wanted to clear previous result and update the new result.
Search
<table class="table table-responsive table-hover table-bordered" id="list_table_json">
<thead>
<tr>
<th>Thumbnail</th>
<th>Title</th>
<th>Duration</th>
<th>Download</th>
</tr>
</thead>
On the start of the success handler, use the below code if you want to keep the first tr (headings) and remove the rest of the data
$("#list_table_json").find("tr:gt(0)").remove();
or use if you want to remove everything
$("#list_table_json").empty();
or another way to remove everything
$("#list_table_json").html('');
How to use?
success: function(result) {
$("#list_table_json").find("tr:gt(0)").remove();
var event_data = '';

export data from Firebase into HTML Table

I'm currently developing an app and using firebase as my database and im trying to export data into a table from a firebase because showing the data in the app in table view is harder than i thought so i turned to HTML table and wrote a code but it is not displaying the data that i want. Just to note that im pretty new to all this so any help would be appreciated. Below is my code:
<html>
<body>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
table {
border-spacing: 5px;
}
</style>
<script src="https://www.gstatic.com/firebasejs/5.2.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyBuJiZZNabXuBO0ac",
authDomain: "",
databaseURL: "",
projectId: "testproject-5",
storageBucket: "",
messagingSenderId: "2568"
};
firebase.initializeApp(config);
</script>
<head>
<title>Quicksol Attendance</title>
</head>
<table style="width:100%" id="ex-table">
<tr id="tr">
<th>Employee ID</th>
<th>Email</th>
<th>Date </th>
<th>Check in Time</th>
<th>Check out Time</th>
</table>
<script>
var database = firebase.database();
database.ref().once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var val = data.val();
content +='<tr>';
content += '<td>' + val.employeeID + '</td>';
content += '<td>' + val.email + '</td>';
content += '<td>' + val.date + '</td>';
content += '<td>' + val.checkintime + '</td>';
content += '<td>' + val.checkouttime + '</td>';
content += '</tr>';
});
$('#ex-table').append(content);
}
});
</script>
</body>
</html>
I have changed the script inside 'database.ref("/").once('value', function (snapshot) {'
Check the working code jsfiddle
// Initialize Firebase
var config = {
apiKey: "AIzaSyBuJiZZNabXuBU-SoRhZFbdecxs0L2O0ac",
authDomain: "testproject-51bd9.firebaseapp.com",
databaseURL: "https://testproject-51bd9.firebaseio.com",
projectId: "testproject-51bd9",
storageBucket: "testproject-51bd9.appspot.com",
messagingSenderId: "256942259748"
};
firebase.initializeApp(config);
var database = firebase.database();
database.ref("/").once('value', function (snapshot) {
if (snapshot.exists()) {
var content = '';
snapshot.forEach(function (data) {
var val = data.val();
var tableData = [];
var sysDate, checkinTime, checkoutTime, email, employeeId;
for (var checkin in val.Checkin) {
for (var date in val.Checkin[checkin]) {
tableData.push({ 'employeeId': checkin, 'email': val.Checkin[checkin][date]['Email'], 'date': date, 'checkinTime': val.Checkin[checkin][date]['Check in Time'] });
}
}
for (var checkout in val.Checkout) {
for (var checkoutDate in val.Checkout[checkout]) {
var item = tableData.find(function (i) { return i.employeeId == checkout && i.date == checkoutDate; })
if (item)
item.checkoutTime = val.Checkout[checkout][checkoutDate]['Checkout Time'];
}
}
console.log(tableData);
tableData.forEach(function (item) {
content += '<tr>';
content += '<td>' + item.employeeId + '</td>';
content += '<td>' + item.email + '</td>';
content += '<td>' + item.date + '</td>';
content += '<td>' + item.checkinTime + '</td>';
content += '<td>' + (item.checkoutTime ? item.checkoutTime : 'NA') + '</td>';
content += '</tr>';
});
});
$('#ex-table').append(content);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.2.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.2.0/firebase-database.js"></script>
<table style="width:100%" id="ex-table">
<tr id="tr">
<th>Employee ID</th>
<th>Email</th>
<th>Date </th>
<th>Check in Time</th>
<th>Check out Time</th>
</table>