i want to repalce the current table after the success of ajax call and show new table.
this is my existing table:
<div class="container">
<h2 class="well col-lg-4">Booking History</h2>
<table id="tab" class="table table-bordered danger table-hover" style="color:orangered">
<thead>
<tr>
<th>S.N</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Booking Date</th>
<th>Booked On</th>
<th>Vehile Number</th>
<th>Parking Slot no.</th>
</tr>
</thead>
<tbody>
#{ int i = 1;}
#foreach (var item in Model)
{
<tr>
<td>#i</td>
<td>#item.firstName</td>
<td>#item.lastName</td>
<td>#item.email</td>
<td>#DateTime.Parse(item.bookingDate).ToString("dd MMM yyyy")</td>
<td>#DateTime.Parse(item.bookedOn).ToString("dd MMM yyyy")</td>
<td>#item.vehicleNo</td>
<td>#item.parkingSlot_id</td>
</tr>
i++;
}
</tbody>
</table>
<div class="text-center">
#Html.PagedListPager(Model, page => Url.Action("SearchBooking", new { page, fromDate = ViewBag.fromD,toDate= ViewBag.toD }))
</div>
</div>
This is my script:
<script>
$(document).ready(function () {
$('#searchByEmail').on('click', function () {
var emailData = $('#emailValue').val();
$.ajax({
type: "POST",
url: "/Admin/SearchByEmail",
dataType: "JSON",
data: { email: emailData },
success: function (result) {
if (result != 0) {
JSON.stringify(result);
var tr;
tr = $('<tr/>');
tr.append("<th>First Name </th>");
tr.append("<th>Last Name </th>");
tr.append("<th>Email</th>");
tr.append("<th>License No.</th>");
tr.append("<th>Booking Date</th>");
tr.append("<th>Booked On</th>");
tr.append("<th>Vehicle No.</th>");
tr.append("<th>Parking Slot No.</th>");
$('table').append(tr);
for (var i in result) {
tr = $('<tr/>');
tr.append("<td>" + result[i].firstName + "</td>");
tr.append("<td>" + result[i].lastName + "</td>");
tr.append("<td>" + result[i].email + "</td>");
tr.append("<td>" + result[i].licenseNo + "</td>");
tr.append("<td>" + result[i].bookingDate.slice(0, -12) + "</td>");
tr.append("<td>" + result[i].bookedOn.slice(0, -12) + "</td>");
tr.append("<td>" + result[i].vehicleNo + "</td>");
tr.append("<td>" + result[i].parkingSlot_id + "</td>");
$('table').append(tr);
}
}
},
error: function () {
alert('failure');
}
})
$('#emailValue').val('');
})
});
</script>
try this
use $("#tab").html('') before you append table
Like,
$("#tab").html('');
$("#tab").append(NewTable);
Related
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");
}
});
I want to know something in Laravel. I want a dropdown for classes so when the user selects any class and press the submit button then the users related to that specific class will be displayed below in the table... Is it possible?
Below is the code I did for getting the data but I want this data to refer to my table in the HTML because there is something more I want and I can't add those things to the ajax table
//My ajax
$(document).ready(function() {
$('select[name="students_class_id"]').on('change', function() {
var classID = $(this).val();
if(classID) {
$.ajax({
url: '/myform/ajax/'+classID,
type: "GET",
dataType: "json",
success:function(data) {
var markup = '';
$.each(data, function(key, value) {
markup += '<tr> <td>' + value.id + '</td> <td>' + value.student_id + '</td> <td>' + value.first_name+ ' ' + value.last_name + '</td> <tr>';
});
$('table[id="studentsData"]').html(markup);
}
});
}
});
});
//Controller
public function index(Request $request){
$classes = StudentsClass::pluck('class_name', 'id')->all();
return view('admin.students.attendance.index', compact( 'classes'));
}
public function mytableAjax($id) {
$students = Student::where('students_class_id', $id)->get();
return json_encode($students);
}
//My view
<select name="students_class_id" class="form-control" style="width:350px">
<option value="">--- Select State ---</option>
#foreach ($classes as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
<table id="studentsData" class="table table-striped table-bordered table-list-search">
<thead>
<tr>
<th>#</th>
<th>Student ID</th>
<th>Student Name</th>
<th>Attendance</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="form-group">
<select class="form-control" id="gender">
<option>Present</option>
<option>Absent</option>
<option>Leave</option>
</select>
</div>
</td>
</tr>
</tbody>
</table>
<a class="fas fa-folder-open btn btn-success float-right mb-4 mr-2"> Save</a>
</div>
Check the following code that will add the attendance column for every row :
$(document).ready(function() {
$('select[name="students_class_id"]').on('change', function() {
var classID = $(this).val();
if (classID) {
$.ajax({
url: '/myform/ajax/' + classID,
type: "GET",
dataType: "json",
success: function(data) {
var attendance = `<div class="form-group">
<select class="form-control" id="gender" name="attendance[]">
<option>Present</option>
<option>Absent</option>
<option>Leave</option>
</select>
</div>`;
var markup = '';
$.each(data, function(key, value) {
markup += '<tr> <td><input type="hidden" value="'+value.id+'" name="id[]">' + value.id + '</td> <td>' + value.student_id + '</td> <td>' + value.first_name + ' ' + value.last_name + '</td> <td> ' + attendance + '</td> <tr>';
});
$('#studentsData tbody').html(markup);
var thead_markup += '<tr> <th>A</th> <th>B</th> <th>C</th> <td>D</th> <tr>';
$('#studentsData thead').html(thead_markup);
}
});
}
});
});
It depends upon your code, if you are using ajax datatables api then here is a similar example:
$(document).ready(function() {
$('#example').DataTable( {
initComplete: function () {
this.api().columns().every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
}
} );
} );
Reference: datatables.net multi filter select
If you are not using datatables api and do not want ajax then use below code and change according to your need:
$("#selectDropdown").on("change", function () {
var value = $(this).val();
$("table tr").each(function (index) {
if (index != 0) {
$row = $(this);
var id = $row.find("td:first").text();
if (id.indexOf(value) != 0) {
$(this).hide();
}
else {
$(this).show();
}
}
});
});
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
});
});
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>
I have a Ajax Jquery function:
function UpdateValue() {
$(document.body).on("change",".quantity", function () {
var ProID = $(this).attr("data");
var Quantity = $(this).val();
$.ajax({
type: "GET", url: "/Cart/UpdateValue",
data: { ProID: ProID, quantity: Quantity },
success: function (data) {
$("#cartbox").html(data);
}
}
);
$.ajaxSetup({
cache: false
});
});
}
call UpdateValue in Cart Controller:
public PartialViewResult UpdateValue(Cart cart,int ProID, int quantity)
{
List<SelectListItem> items = new List<SelectListItem>();
for (int i = 1; i <= 10; i++)
{
items.Add(new SelectListItem { Text = i.ToString(),
Value = i.ToString() });
}
ViewBag.Items = items;
Product product = repository.Products.FirstOrDefault(p => p.ProductID
== ProID);
if (product != null)
{
cart.UpdateItem(product, quantity);
}
CartIndexViewModel ptview = new CartIndexViewModel { Cart = cart,
ReturnUrl = "/" };
return PartialView(ptview);
}
When the ajax function success, it returns UpdateValue View. But the Dropdown List always changes the same in each row. How can i pass the selected value from the Index View after ajax update?
Here is my UpdateValue View Code:
<table id="cartbox">
<thead>
<tr>
<th>Tên hàng</th>
<th>Số lượng</th>
<th>Đơn giá</th>
<th colspan="2" style="width:70px">Thành tiền</th>
</tr>
</thead>
<tbody>
#foreach (var line in Model.Cart.Lines)
{
<tr>
<td>#line.Product.Name
</td>
<td>#Html.DropDownList("Quantity", new SelectList(ViewBag.Items as System.Collections.IList, "Value", "Text", line.Quantity), new { data = line.Product.ProductID, #class = "quantity" })</td>
<td style="color:#3A9504;margin-left:3px">#string.Format("{0:00,0 VNĐ}", line.Product.Price)</td>
<td>#string.Format("{0:00,0 VNĐ}", (line.Quantity * line.Product.Price))</td>
<td align="center" style="width:10px"><img src="#Url.Content("~/Content/Images/delete.png")" style="padding-right:10px" /></td>
</tr>
}
</tbody>
<tfoot>
<tr style="border-top-style:solid;border-top-color:#DFDFDF;border-top-width:1px;">
<td colspan="3" align="right" style="border-right-color:#808080;border-right-style:solid;border-right-width:1px;text-align:right"><b>Tổng tiền:</b></td>
<td style="text-align: center"><b>#string.Format("{0:00,0 VNĐ}", Model.Cart.ComputeTotalValue())</b></td>
<td></td>
</tr>
</tfoot>
</table>
If I understand you correctly then your problem is that after updating the data in the dropdown list you lose the selection in that dropdown list?
If so then you would need to add this to your success handler in JavaScript:
success: function (data) {
$("#cartbox").html(data);
$("#cartbox").find(".quantity").val(Quantity);
}