Spring view page detail with ajax - 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");
}
});

Related

jquery dynamic created th and tr from ajax call response

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

AJAX Post to handler functions in Razor pages

So the situation is such:
I am using data-tables in my .cshtml file. I have managed to add records via a modal but the issue is when i want to populate a modal in order to edit the data from a row. I do not wish to fetch data from the row but instead do a Ajax request to fetch the data. Below shows the structure of my table
<table id="example" class="table table-striped table-bordered dt-responsive display nowrap" cellspacing="0">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>Email</th>
<th>Status</th>
<th>Roles</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (var user in Model.Users)
{
<tr>
<td>#user.FirstName</td>
<td>#user.LastName</td>
<td>#user.UserName</td>
<td>#user.Email</td>
<td>#user.status</td>
<td>
#{ if (user.Roles.Contains("SuperAdmin"))
{
<span class="badge badge-danger">SA</span> }
else if (user.Roles.Contains("Admin"))
{
<span class="badge badge-danger">ADMIN</span> }
else if (user.Roles.Contains("Moderator"))
{
<span class="badge badge-warning">MOD</span> }
else if (user.Roles.Contains("Basic"))
{
<span class="badge badge-success">BASIC</span> }
}
</td>
<td>
#{ if (user.Roles.Contains("SuperAdmin"))
{
<span class="badge badge-warning">Locked</span> }
else
{
<button class="btn btn-sm btn-dark details" id="useredit" data-id="#user.UserId">Edit</button>
<a class="btn btn-primary btn-sm" asp-area="Identity" asp-page="/Account/UserRoles" asp-route-userId="#user.UserId">Manage Roles</a> }
}
</td>
</tr>}
</tbody>
</table>
When i click on the edit button the follow code gets executed
$("button.details").on('click', function () {
console.log({ "id": $(this).attr("data-id") });
var userid = $(this).attr("data-id");
$.ajax({
type: "POST",
url: "/Identity/Account/Users?handler=UsersAsJson",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { id:userid },
contentType: "json; charset=utf-8",
success: function (regions) {
console.log(regions)
},
failure: function (response) {
alert(response);
}
});
});
And this is the handler function below
public async Task<IActionResult> OnPostUsersAsJsonAsync(string? id)
{
System.Diagnostics.Debug.WriteLine("id passed",id);
return new JsonResult(id);
}
Can anyone tell me how do we pass the id from the ajax request into the handler function? cause at the moment its not posting to the OnPostUsersAsJsonAsync function.
Also note i have tried getJSON without any success.
For you do not have a form,be sure you have added token like below:
<button class="btn btn-sm btn-dark details" id="useredit" data-id="#user.UserId">Edit</button>
#Html.AntiForgeryToken()
Change your js like below:
#section Scripts
{
<script>
$("button.details").on('click', function () {
console.log({ "id": $(this).attr("data-id") });
var userid = $(this).attr("data-id");
$.ajax({
type: "POST",
url: "/Identity/Account/Users?handler=UsersAsJson",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { id: userid },
//contentType: "json; charset=utf-8", //remove this line
success: function (regions) {
console.log(regions)
},
failure: function (response) {
alert(response);
}
});
});
</script>
}
Startup.cs:
services.AddRazorPages();
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN"); //be sure add this line
Result:

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
});
});

AJAX Post to Update List in View

I have a List in my model. The view is bound to the model. I am trying to populate the List through ajax. And then I have a 'submit' button on the form which should submit the entire model. While submitting the entire model, the list value is 'null'??
I am getting the response data from the controller through Json. The response data is not bound to the model.
<table id="tblTable" style="border-width:1px;border-style:solid" >
<tr style="border-width:1px;border-style:solid">
<th>
#Html.Label("Col1")
</th>
<th>
#Html.Label("Col2")
</th>
</tr>
<tbody>
#if (Model != null && Model.Operations!= null && Model.Operations.Count > 0)
{
foreach (var item in Model.Operations)
{
<tr style="border-width:1px;border-style:solid">
<td style="border-width:1px;border-style:solid">
#Html.DisplayFor(modelItem => item.Col1)
</td>
<td style="border-width:1px;border-style:solid">
#Html.DisplayFor(modelItem => item.Col2)
</td>
</tr>
}
}
</tbody>
</table>
My controller that responds to teh ajax request:
[HttpPost]
public JsonResult UploadFile(HttpPostedFileBase file, Model model)
{
//extract file contents into the operations list
model.Operations = new List<Operations>();
model.Operations.Add(blah..blah)
return Json(model);
}
Issue is, I have to populate the list via ajax, but post the complete model along with the ajax-retrieved data.
Update: JS CODE:
$(document).ready(function () {
$('#fileupload').fileupload({
dataType: 'json',
url: '/Summary/UploadFile',
autoUpload: true,
done: function (e, data) {
var operations = data.result.Operations;
var tbl = $('#tblTable');
$.each(operations, function (key, val) {
$('<tr><td>' + val.col1 + '</td>' + '<td>' +
val.col2 + '</td><tr>').appendTo(tbl);
});
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('.progress .progress-bar').css('width', progress + '%');
});
});

Duplicated List of DropdownList when ajax update?

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);
}

Resources