jquery dynamic created th and tr from ajax call response - laravel

I want to create table head dynamic and table rows dynamic also, I don't where I am doing wrong.
I'm using Laravel for the data population of Data tables.
This is my response. I have two response, one for table heads and other table rows.
{"draw":0,"recordsTotal":14,"recordsFiltered":4,"data":[{"leaveTypeId":20,"leaveName":"Annual Leave"},{"leaveTypeId":7,"leaveName":"Hajj leave"},{"leaveTypeId":19,"leaveName":"TOIL"},{"leaveTypeId":11,"leaveName":"Unpaid leave"},{"leaveTypeId":2,"leaveName":"Sick Leave"},{"leaveTypeId":5,"leaveName":"Paternity leave"},{"leaveTypeId":6,"leaveName":"Maternity leave"}
,"emp":[{"id":327,"empName":"Abbas "},{"id":162,"empName":"Abdo"},{"id":407,"empName":"Abdo"},{"id":411,"empName":"Abdo"},{"id":219,"empName":"Abdu"},{"id":334,"empName":"Abdul Hakeem "},{"id":330,"empName":"Abdul Kareem "},{"id":412,"empName":"Abdulaleem"},{"id":246,"empName":"Abdulaziz"},{"id":301,"empName":"Abdulfatah"},{"id":100,"empName":"Abdulgani"},{"id":364,"empName":"Abduljaleel "},{"id":95,"empName":"Abdulkareem"},{"id":287,"empName":"Abdulkareem"},{"id":413,"empName":"Abdulkarim"},{"id":711,"empName":"Abdulkhaliq"},{"id":15,"empName":"Abdullah"},{"id":19,"empName":"Abdullah "},{"id":69,"empName":"Abdullah"},{"id":70,"empName":"Abdullah"},{"id":71,"empName":"Abdullah"},{"id":96,"empName":"Abdullah "},{"id":97,"empName":"Abdullah "},{"id":200,"empName":"Abdullah "},{"id":243,"empName":"Abdullah"},{"id":244,"empName":"Abdullah"},{"id":249,"empName":"Abdullah"},{"id":258,"empName":"Abdullah"},{"id":455,"empName":"Abdullah "},{"id":546,"empName":"Abdullah "},{"id":591,"empName":"Abdullah "},{"id":708,"empName":"Abdullah"},{"id":542,"empName":"Abdulmalik"}}
at balde page, I'm using like this.
<table id="LeaveSummaryGrid" class="table table-bordered table-striped">
<thead>
</thead>
<tbody>
</tbody>
</table>
And my ajax call like this.
$.ajax({
type: "get",
url: url_search,
//dataType:"json",
//data: data,
success: function (response)
{
var count = 1;
var trHTML = '';
$.each(response.data, function (key,value) {
trHTML +=
'<tr><th> EmpName' +
'</th><th colspan="3">' + value.leaveName +
'</th></tr>' +
'<tr><th>' +
'</th><th>Ent.' +
'</th><th>Ava.' +
'</th><th>Bal.' +
'</th></tr>'
;
count++;
/*header.append(
$('<th colspan="3"> jh </th></tr><tr><th>Ent.</th><th>Ava.</th><th>Bal.</th>')
);*/
});
$('#LeaveSummaryGrid thead').append(trHTML);
}
});
But this populating into rows.
I want the desired result like below shown in image.
enter image description here
EmpName
Annual Leave
Sick Leave
TOIL Leave
Maternity Leave
Paternity Leave
Each Leave type has sub table head i.e. Entitle, Availed, Balance

<table id="LeaveSummaryGrid" class="table table-bordered table-striped">
<thead id="thead">
</thead>
<tbody>
</tbody>
</table>
$.ajax({
type: "get",
url: url_search,
//dataType:"json",
//data: data,
success: function (response)
{
$.each(response.data, function (key,value) {
$('#thead').append("<tr><th> EmpName'+ value.leaveName +'</th></tr>" //and so on ...);
/*header.append(
$('<th colspan="3"> jh </th></tr><tr><th>Ent.</th><th>Ava.</th><th>Bal.</th>')
);*/
});

I resolve by myself and work well.
JS would be
$.ajax({
type: "get",
url: url_search,
//dataType:"json",
//data: data,
success: function (response)
{
var count = 1;
var trHTML = '';
var thLeave ='';
var thSub ='';
$.each(response.data, function (key,value) {
thLeave+= '<th colspan="3">'+value.leaveName+'</th>';
thSub+= '<th>Ent.</th>' +
'<th>Ava.</th>' +
'<th>Bal.</th>';
});
var table = `
<table id="LeaveSummaryGrid" class="table table-bordered table-striped">
<tr>
<th rowspan="2">EmpName</th>`+
thLeave+
`</tr>
<tr>`+
thSub+
`</tr>
</table>
`;
$('#Table').append(table);
}
});
AND HTML would be
<div class="table-responsive" id="Table">
</div>
so it created.
enter image description here

Related

Spring view page detail with ajax

I would like to know how you would make an ajax call to another page to show a listing containing the service data
Models.html
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Model</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Controller
#CrossOrigin
#GetMapping("/cars/{id}/model")
public List<Model> getModels(#PathVariable Long id) {
Optional<Car> car = carRepository.findById(id);
return car.get().getModels();
}
Json
$('table').on('click', 'button[id="model"]', function(e){
var id = $(this).closest('tr').children('td:first').text();
$.ajax({
type:"GET",
enctype: 'application/json',
url:"/cars/" + id + "/model",
success: function(data){
var models = JSON.parse(JSON.stringify(data));
for (var i in models) {
console.log(i);
}
},
error: function(err) {
console.log("Error");
}
});

Laravel : Update Database using Ajax. What's I should to do next?

I need the guidance of somebody to help me building the function Update Database when using AJAX. When I click the button Accept so an Ajax request will send to the server and server will execute UPDATE value of field post_status. At the start, field post_status has value is "pending", and after execute query UPDATE so the value will change to "accepted".
What's I should do next? Please help me.
Thank you so much for help.
The database of the Posts table:
post_id user_id title content DateTime post_status
1 1 Title 1 Content 1 Time pending
2 2 Title 2 Content 2 Time pending
3 3 Title 3 Content 3 Time pending
4 4 Title 4 Content 4 Time pending
5 5 Title 5 Content 5 Time pending
The View:
<table class="table table-bordered">
<thead class="thead-inverse">
<tr>
<th>Post ID</th>
<th>User ID</th>
<th>Name User</th>
<th>Title</th>
<th>Content</th>
<th>Datetime</th>
<th>Status</th>
<th>Accept</th>
</tr>
</thead>
<tbody>
#foreach ($posts as $row)
<tr id="{{ $row->post_id }}">
<td>{{$row->post_id}}</td>
<td>{{$row->user_id}}</td>
<th>{{$row->users->name}}</th>
<td>{{$row->post_title}}</td>
<td>{{$row->post_content}}</td>
<td>{{$row->post_datetime}}</td>
<td>{{$row->post_status}}</td> {{-- The status of post that I wanna change the value to "accepted" --}}
<td>
<button class="btn btn-success accept-btn" data-postID="{{$row->post_id}}">Accept</button>
</td>
</tr>
#endforeach
</tbody>
</table>
The code Javascript:
<script>
$(document).ready(function () {
$('.accept-btn').click(function(){
var postId = $(this).attr('data-postID');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "{{route('posts.list_post_ajax')}}",
data: { postId: postId },
dataType: 'JSON',
success :function(response) {
console.log(response);
},
});
})
});
</script>
The function list_post_ajax of Controller:
public function list_post_ajax(Request $request)
{
if(request()->ajax()){
$postId = $request->get('postId');
return response()->json(['success'=>$postId]);
// What's I should do next?
// Pls help me.
}
}
There are so many ways to do it. This one will work following your code. Use $myObject->save(); to save a new record or update a old one.
Change on view
<td id="td{{$row->post_id}}">{{$row->post_status}}</td>
On Controller
$postId = $request->get('postId');
$post = App\Post::find($postId);
$post->post_status= 'accepted';
$post->save();
return response()->json(['success'=>$postId,'message'=>'accepted']);
On JS
$.ajax({
type: "POST",
url: "{{route('posts.list_post_ajax')}}",
data: { postId: postId },
dataType: 'JSON',
success :function(response) {
console.log(response);
$('td'+postId).html(response.message);
},
});
Edit: I update my answer on Controller. You should take a look Eloquent Documentation

Header of grid stays after removal of all data of grid laravel

I have a design of grid in controller that displays me all data of selected check boxes.
This grid gets appended to a span through ajax.
While performing a delete request, one by one my data in grid gets deleted,
but the grid header stays as it is.
This is my design of grid in controller:
$res_div = '';
$res_div.='<table width="100%" border="0" class="table table-striped table-bordered table-hover">';
$res_div.='<tr>
<th width="100%">SublawId</th>
<th width="100%">Sublawname</th>
<th width="100%">View</th>
<th width="100%">Update</th>
</tr>';
foreach ($law as $sublaw)
{
$law_details = DB::table('tbl_law_sub_master')->where('id', $sublaw->id)->select('*')->first();
$res_div.='<tr>
<td>
<strong>'.$law_details->lms_id.'</strong>
</td>
<td>
<strong>('.$law_details->sub_law_name.')</strong>
</td>
<td align="center">
<input type="checkbox" id="cb1" onclick="ts(this)" class="cb1" name="viewsub_'.$sublaw->id.'">
</td>
<td align="center">
<input type="checkbox" id="cb1" onclick="ts(this)" class="cb1" name="updatesub_'.$sublaw->id.'">
</td>
</tr>';
}
$res_div.='</table>';
$data=array(
'res_div'=>$res_div,
'law'=>$law
);
return json_encode($data);
my ajax request on blade:
$.ajax({
url: "{{ URL::to('staff/staffpostsublawsdata') }}?sub_law_id="+sublaw_ids.join(),
type: 'POST',
dataType: "json",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
var res_sublaw_content=returndata.res_div;
var data = document.getElementById("append_sublaw_grid").innerHTML = ""; $('#append_sublaw_grid').append(res_sublaw_content);
return false;
}
});
On deletion all data gets deleted one by one from grid, but its header stays..
A screenshot:
Everytime you remove a row u can count the number of rows left using
var rowCount = $('.table tbody tr').length;
if rowcount goes to 0 then just hide the table using
$('.table').hide()
Working example:
Put this code in the function where you delete the rows
var rowCount = $('.table tbody tr').length;
if( rowcount == 0){
$('.table').hide();
}

data getting lost after any operation on data-table while loading rows using ajax

I am fetching dataTable rows using Ajax from my controller in CodeIgniter.
I have fetched it successfully, but the problem is rows get lost while doing any operation on dataTable like sorting, searching.
But after refreshing a page it came back.
Here is my Ajax Script:
$('#dataTable_choose').DataTable({
responsive: true
});
$('body').on('click', '.getJobApplication', function(e) {
//alert();
var noteId = $(this).data('noteId');
var note_id = { id : noteId }
$.ajax({
type: 'POST',
async: true,
dataType: 'Json',
url: get_table_rows,
data: note_id,
success: function (response) {
if(response.length > 0){
for (i = 0; i < response.length; i++) {
innerhtml += "<tr>" +
"<td>"+response[i].column1+"</td>" +
"<td>"+response[i].column2+"</td>" +
"<td>"+response[i].column3+"</td>" +
"<td>"+response[i].column4+"</td>" +
"<td><span class='label label-info'>"+column5+"</span></td>" +
"<td>"+
"<button type='button' class='btn btn-success waves-effect waves-light' data-secid="+response[i].id2+" " +
" data-fiid = "+response[i].id+" >Choose</button>" +
"</td>" +
"</tr>";
$('#table_body').html(innerhtml);
}
} else {
console.log('error');
}
},
error: function (msg)
{
console.log('error');
}
});
});
Here is the Table HTML Code:
<table id="dataTable_choose" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Job Title</th>
<th>Qualification</th>
<th>Qualification Major</th>
<th>Candidate Name</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody id="table_body">
</tbody>
</table>
After changing your DataTable's content with ajax, you need to clear the DataTable and redraw it. Below is a code that works for me (tried to add your ID's, please verify that they are correct and implement right in your code):
success: function (response) {
//DRAW YOUR innerhtml HERE, as you already do
$("#dataTable_choose").dataTable().fnClearTable(); //clear the table
$('#dataTable_choose').dataTable().fnDestroy(); //destroy the datatable
$('#table_body').html(innerhtml); //add your new data
$('#dataTable_choose').DataTable({ //redraw with new data
//YOUR OPTIONS HERE
});
});

Can't get sibling element text with jQuery

I have the following markup:
<table>
<tr>
<td>2 <i class="increase_quantity hidden-print icon-plus-sign"></i> <i class="decrease_quantity hidden-print icon-minus-sign"></i></td>
<td class="price_setup">0.0</td>
</tr>
</table>
jQuery
$(document).on('click', '.increase_quantity', function() {
alert('Setup Price: ' + $(this).closest('td').siblings('td.price_setup').text());
return false;
});
The problem is that the result is blank. I was actually trying to parseFloat but kept getting NaN so took that out for just now.
Update
The tr is being appended to the table via an ajax request
// ajax callback
// append result of ajax request
$('#line_items tbody:last').append(data);
Fiddle: http://jsfiddle.net/f49V8/11/ (which works)
Ajax response is valid HTML containing the markup from above.
Edit - Complete Code
I've been through this with a fine tooth comb and honestly can't see anything wrong so going to post the complete relevant code in the hope of someone spotting something.
Rails
class PriceListItemController < ApplicationController
def get_info
if params[:id] != ''
product = PriceListItem.find_by_id(params[:id])
total = product.price_setup + (product.price_rental * product.contract_length)
next_item = params[:no_items].to_i + 1
output = '<tr><td>' + next_item.to_s + '</td><td>' + product.product_type + '</td><td>' + product.description + '</td><td>1 <i class="increase_quantity hidden-print icon-plus-sign"></i></td><td class="price_setup">' + product.price_setup.to_s + '</td><td class="price_rental">' + product.price_rental.to_s + '</td><td class="contract_length">' + product.contract_length.to_s + ' months</td><td class="total">' + total.to_s + '</td></tr>'
render :text => output
end
end
end
HTML
<div class="row-fluid">
<table id="line_items" class="table table-striped table-hover">
<thead>
<tr>
<th>#</th>
<th>Item</th>
<th>Description</th>
<th>Quantity</th>
<th>Setup Cost</th>
<th>Rental Cost</th>
<th>Contract Term</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr id="blank">
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
</tbody>
</table>
</div>
jQuery
var no_items = 0;
$('#add_product').click(function() {
$.ajax({
url: '/price_list_item/get_info',
data: { id: $('#products_list').val(), no_items: no_items },
dataType: 'html',
type: "GET",
cache: false,
success: function(data) {
no_items++;
// append result of ajax request
$('#line_items tbody:last').append(data);
// remove blank row
$('#blank').remove();
var sub_total = 0;
var vat;
// update totals
$('.total').each(function(i) {
sub_total += parseFloat($(this).text());
});
vat = sub_total * 0.2;
total = vat + sub_total;
$('#sub_total').text('£' + sub_total);
$('#vat').text('£' + vat);
$('#total').text('£' + total);
},
error: function(){
alert('An error occurred, please refresh the page and try again');
}
});
});
$(document).on('click', '.increase_quantity', function() {
var quantity = parseInt($(this).parent().text());
var new_quantity = quantity + 1;
if (new_quantity > 1) {
$(this).closest('td').html(new_quantity + ' <i class="increase_quantity hidden-print icon-plus-sign"></i> <i class="decrease_quantity hidden-print icon-minus-sign"></i>');
// readjust total for this line item
var setup_cost = parseFloat($(this).closest('td').siblings('td.price_setup').text());
var rental_cost = parseFloat($(this).closest('td').siblings('td.price_rental').text());
var contract_length = parseInt($(this).closest('td').siblings('td.contract_length').text());
alert(setup_cost);
var total = setup_cost + (rental_cost * contract_length);
$(this).parent().parent().children('.total').text(total);
// update totals
$('.total').each(function(i) {
sub_total += parseFloat($(this).text());
});
vat = sub_total * 0.2;
total = vat + sub_total;
$('#sub_total').text('£' + sub_total);
$('#vat').text('£' + vat);
$('#total').text('£' + total);
}
return false;
});
<script>
jQuery(document).ready(function()
{
jQuery(".increase_quantity").click(function()
{
alert('Setup Price: ' + $(this).parent('td').siblings('td.price_setup').html());
});
});
</script>
<table>
<tr>
<td>2
<i class="increase_quantity hidden-print icon-plus-sign">12</i>
<i class="decrease_quantity hidden-print icon-minus-sign"></i>12</td>
<td class="price_setup">10.0</td>
</tr>
</table>

Resources