I'm using thyme leaf. I have a table that displays dynamic records. I have tried 2 approaches to display the records, but the values are not binding.
Approach - 1
Using JQuery
$().ready(function () {
getTableDetails();
});
function getTableDetails() {
try {
var ajaxCall;
ajaxCall = $.ajax({
url: /getTableDetails
type: 'GET',
async:false,
dataType: 'json'
});
ajaxCall.done(function (data, textStatus, jqXHR) {
alert(JSON.stringify(data));
$.each(data, function (i, p) {
$('#details').append($('<tbody></tbody>').val(p).html(p));
});
});
ajaxCall.fail(function (jqXHR, textStatus, errorThrown) {
// handle failure cases
alert(textStatus+errorThrown);
});
} catch (e) {
}
}
HTML File
<table class="indi-data-table__table">
<thead>
<tr>
<th scope="col" class="datatable-column-width125" role="columnheader">
<div class="indi-data-table__column-heading">ID</div>
</th>
<th scope="col" class="datatable-column-width150" role="columnheader">
<div class="indi-data-table__column-heading">NAME</div>
</th>
</tr>
</thead>
<tbody id="details">
<tr th:each="row : ${tableDetailList}">
<td th:text="${row.id}"/>
<td th:text="${row.name}"/>
</tr>
</tbody>
</table>
Approach - 2
Using Model getAttribute from Java
#RequestMapping(value = "/getTableDetails", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<DataEntity> getTableDetails(Model model) throws JsonProcessingException {
List<DataEntity> tableDetailList = new ArrayList<>();
try {
tableDetailList.addAll(repoCall);
} catch (Exception ex) {
ex.getCause().printStackTrace();
}
model.addAttribute("tableDetailList", tableDetailList);
return tableDetailList;
}
I have also tried
<tr th:each="row : ${tableDetailList}">
<td th:text="${row.getId()}"/>
<td th:text="${row.getName()}"/>
</tr>
But, none of them is actually binding the values, I am getting the response from the API.
Any help is much appreciated.
Thank you!
Related
I want to put the user object I received as Ajax into {{#user}} in mustache and render it on the screen.
<table class="table table-horizontal table-bordered">
<thead class="thead-strong">
<tr>
<th>user number</th>
</tr>
</thead>
<tbody id="tbody">
{{#users}}
<tr>
<td>{{id}}</td>
</tr>
{{/users}}
</tbody>
</table>
this is conroller
#PostMapping("/api/v1/eduPosts/registerAdminToUser")
public List<User> registerAdminToUser(#RequestBody UserRegisterRequestDto userRegisterRequestDto){
List<User> users=userService.registerAdminToUser(userRegisterRequestDto);
System.out.println(users);
return users;
}
this is index.js
update : function () {
var data = {
adminId: $('#adminId').val(),
userId: $('#userId').val()
};
//var id = $('#id').val();
$.ajax({
type: 'POST',
url: '/api/v1/eduPosts/registerAdminToUser',
dataType: 'json',
contentType:'application/json; charset=utf-8',
data: JSON.stringify(data)
}).done(function(data) {
$.each(data, function(idx, val) {
alert(idx + " " + val.id);
console.log(idx + " " + val.id)
});
alert(JSON.stringify(data))
}).fail(function (error) {
alert(JSON.stringify(error));
});
}
Should I change the js file? Or do I have to change the mustache template?
If I print out the user object in the index.js file, the data is being rendered properly.
Thanks!
I have a Html table(instead of Grid control I used HTML table) having multiple rows with one drop down and one textbox control.I want auto complete function for that text box.I implemented the following code for auto complete but it is firing for only first row.The rows are added Dynamically (in jquery) its not workig for those rows.
<table class="table table-bordered table-hover datatable-highlight" id="tWDE_Items">
<thead>
<tr>
<th style="display:none">ItemId</th>
<th>Item Name</th>
<th>UOM</th>
</tr>
</thead>
<tbody>
#foreach (var Item in Model.Data_Wde_ItemGrid)
{
<tr class="datarow">
<td style="display:none">#Item.Item_Id</td>
<td>#Html.EditorFor(m => Item.Item_Name, new { htmlAttributes = new { #class = "form-control" } }) </td>
<td>#Html.DropDownListFor(m => Item.UOM_Id, new SelectList(Item.UOMDetails, "UomId", "UomName"), htmlAttributes: new { #class = "form-control", id = "UomId" })</td>
</tr>
}
</tbody>
</table>
And Jquery code which I tried is as follows.
$(function () {
$('#Item_Item_Name').autocomplete({
source: function (request, response) {
debugger;
var param = { ItemName: $('#Item_Item_Name').val() };
$.ajax({
url: "/WDE/GetAutoCompleteItemList",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
val: item.split('÷')[0],
label: item.split('÷')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
change: function (e, i) {
if (i.item) {
}
else {
$('#Item_Item_Name').val('');
$('#Item_Item_Id').val('');
}
},
select: function (e, i) {
debugger;
$('#Item_Item_Name').val(i.item.label);
$(this).closest("tr").find("td").eq(2).html(i.item.val);
},
minLength: 1
});
});
You're saying
having multiple rows with one drop down and one textbox control. I want auto complete function for that text box
and I'm also seeing
$('#Item_Item_Name').autocomplete(...
Are you giving the same id to every textbox? If so, that will not work. Ids have to be unique. Jquery will assume you have only 1 and fire/listen to events only for that 1 textbox.
Consider rewriting your JS using classes for the textbox instead.
Below is the view modal where I am getting the ajax response and load to the obserable value.
var userManagementVM = {
responseSetUpData: ko.observable({
userList: ko.observable(),
userListViewModel: ko.observableArray(),
MeetingId: ko.observable(),
MeetingTypeId: ko.observable(),
MeetingType: ko.observable()
}),
SetListOfUserInRoles: function () {
var self = this;
var ajaxUrl = ApplicationRootUrl("UserRoleManagement", "UserManagement");
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: ajaxUrl,
dataType: "json",
success: function (data) {
self.responseSetUpData(data);
console.log(self.responseSetUpData())
},
error: function (err) {
}
});
}
}
$(document).ready(function () {
ko.applyBindings(userManagementVM, document.getElementById("rightdash-container"));
userManagementVM.SetListOfUserInRoles();
});
The response from the ajax is successfully loaded to the obserable value. Below is the output of the console
HTML code
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Users</th>
<th scope="col">Role</th>
</tr>
</thead>
<tbody data-bind="foreach: responseSetUpData.userListViewModel">
<tr>
<td><input class="form-check-input" type="checkbox" data-bind="checked: SelectedUser"><span data-bind="text: $data.FirstName"></span></td>
<td><select data-bind="options: $data.Roles,optionsText: 'Name',value: $data.SelectedRoleId,optionsCaption: '-- Select Role --'"></select></td>
</tr>
</tbody>
</table>
The value is not bind to the UI.
You need to get the value of the observable - responseSetUpData() in the binding:
<tbody data-bind="foreach: responseSetUpData().userListViewModel">
Otherwise you are trying to get userListViewModel from the observable function object :-)
<table class="table table-bordered table-striped table-hover datatable">
<thead>
<tr>
<th>ID</th>
<th>organisation Name</th>
<th>User name</th>
<th>Email</th>
<th>Contact No</th>
<th>IP</th>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr class="success"> <td>3</td>
<td>Harshit </td>
<td>AtulSaini</td>
<td>arpitkumar#gmail.com</td>
<td>786048</td>
<td>::1</td>
<td>14/03/2015</td><td><button id="status"><span class="label label-success">Active</span></button></td></tr><tr class="none"> <td>4</td>
<td>Meghaa.co.edu</td>
<td>megha</td>
<td>meghaa16#gmail.com</td>
<td>786048</td>
<td>::1</td>
<td>14/03/2015</td><td><button id="status"><span class="label label-success">Active</span></button></td></tr>
</tbody>
</table>
Hello to all I want last if condition to execute on the server response which alters the res variable
The problem is when i put the whole if block of code in ajax success then variable "this" value get changed which disables the code to change the tr
and if i keep it outside as i have done here then the variable res gets destroyed as it is in a success function
<script type="text/javascript">
$(document).ready(function() {
$(".label").click(function() {
var idx = $(this).parents("tr").find('td:first').html();
var status = $(this).parents("tr").find('span').html();
var cname=$(this).parents('tr').attr("class");
alert(this);
$.ajax({
url : "scripts/update.php",
type : 'GET',
data : {
"status" : status,
"id" : idx
},
error : function(xhr, status, error) {
alert(error);
},
success : function(entry) {
var res = entry;
}
});
alert(status);
if (status == 'Active') {
$(this).parents("tr").removeClass(cname);
$(this).parents("tr").addClass("warning");
$(this).removeClass("label-success");
$(this).addClass("label-warning");
$(this).text("Deactive");
alert("Account Deacivated");
} else {
$(this).parents('tr').removeClass(cname);
$(this).parents('tr').addClass("success");
$(this).removeClass("label-warning");
$(this).addClass("label-success");
$(this).text("Active");
alert("Account Acivated");
}
});
});
</script>
Thanx in advance for your help...
I'm not exactly sure what you are trying to achieve (e.g. what kind of data is stored in res / entry). But maybe the following will help you:
<script type="text/javascript">
$(document).ready(function() {
$(".label").click(function() {
// store reference for later use (and to avoid creating the same object multiple times)
var item = $(this);
// use the previously stored jQuery item instead of recreating it every time with $(...)
var idx = item.parents("tr").find('td:first').html();
var status = item.parents("tr").find('span').html();
// ...
$.ajax({
url: "scripts/update.php",
type: 'GET',
data: {
"status": status,
"id": idx
},
error: function(xhr, status, error) {
alert(error);
},
success: function(entry) {
// `item` will still reference to the label you clicked on
}
});
});
});
</script>
Try this out :
...
var $this = $(this);
$.ajax({
url : "scripts/update.php",
type : 'GET',
data : {
"status" : status,
"id" : idx
},
error : function(xhr, status, error) {
alert(error);
},
success : function(entry) {
changeStatuts(entry, $this);
}
});
var changeStatuts = function(status, ele){
if (status == 'Active') {
ele.parents("tr").removeClass(cname);
ele.parents("tr").addClass("warning");
ele.removeClass("label-success");
ele.addClass("label-warning");
ele.text("Deactive");
alert("Account Deacivated");
} else {
ele.parents('tr').removeClass(cname);
ele.parents('tr').addClass("success");
ele.removeClass("label-warning");
ele.addClass("label-success");
ele.text("Active");
alert("Account Acivated");
}
};
Okay, after reading your comment, maybe something like the following could solve your problem. BUT: Your PHP code seems to be vulnerable against a sql injection
<script type="text/javascript">
$(document).ready(function() {
$(".label").click(function() {
// store reference for later use (and to avoid creating the same object multiple times)
var item = $(this);
// use the previously stored jQuery item instead of recreating it every time with $(...)
var parentRow = item.parents("tr");
var idx = parentRow.find('td:first').html();
var status = parentRow.find('span').html();
$.ajax({
url: "scripts/update.php",
type: 'GET',
data: {
"status": status,
"id": idx
},
error: function(xhr, status, error) {
alert(error);
},
success: function(status) {
if (status == 'Active') {
parentRow.removeClass(cname);
parentRow.addClass("warning");
item.removeClass("label-success").addClass("label-warning").text("Deactive");
alert("Account Deacivated");
} else {
parentRow.removeClass(cname);
parentRow.addClass("success");
item.removeClass("label-warning").addClass("label-success").text("Active");
alert("Account Acivated");
}
}
});
});
});
</script>
I have a table that I need to dynamically add/remove rows from. Each row has a hyperlink in the final column to remove the record. Since you can dynamically add rows after the page loads, occasionally this record won't be found in the database.
When the user clicks on the "Delete" link, an ajax function is called to remove the record from the database. As long as the function server-side function does not crash, the operation will send back as a success.
Once the ajax function's success function is called, I would like to remove the tr from the table.
I can do this with each row that exists in the table once the page loads. The ajax function sends the proper info back to the server, and the tr is removed from the table. However for each tr I add after the delete ajax function will not fire, and the tr is left on the page.
View
<fieldset>
<legend>Agent Ids</legend>
<table id="agentTable">
<thead>
<tr>
<th>State Code</th>
<th>Company Code</th>
<th>Agent ID</th>
<th>Non-Res Biz NY</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.BankListAgentIds)
{
#Html.Partial("AgentIdPartial", item)
}
</tbody>
Add Another
</table>
</fieldset>
Parial View
#model CollectionItemTest.Models.BankListAgentId
#{
Layout = null;
}
#using (Html.BeginCollectionItem("BankListAgentIds"))
{
#Html.HiddenFor(model => model.TableId)
#Html.HiddenFor(model => model.BankID)
<tr>
<td>
#Html.EditorFor(model => model.StateCode)
</td>
<td>
#Html.EditorFor(model => model.CompanyCode)
</td>
<td>
#Html.EditorFor(model => model.NonResBizNY)
</td>
<td>
#Html.EditorFor(model => model.AgentId)
</td>
<td>
#Html.ActionLink("Delete", "", "", new { href = "javascript:void(0)", id = Model.TableId })
</td>
</tr>
}
jQuery
<script type="text/javascript">
$(function() {
$('#agentTable').on('click', 'tr a', function(e) {
$.ajax({
url: '#Url.Action("DeleteRow", "BankList")',
data: { id: $(this).attr('id') },
dataType: 'html',
cache: false,
context: this,
success: function () {
$(this).parents('tr').remove();
}
});
})
});
$(document).ready(function () {
$('.addCode').click(function() {
$.ajax({
url: '#Url.Action("BlankRow", "BankList")',
dataType: 'html',
cache: false,
success: function(html) {
$("#agentTable > tbody").append(html);
}
});
});
});
</script>
Controller Functions
public JsonResult DeleteRow(int id)
{
if (id == 0) return null;
var agent = (from a in db.BankListAgentIds
where a.TableId == id
select a).FirstOrDefault();
if (agent == null) return Json("Agent Id not found", JsonRequestBehavior.AllowGet);
db.BankListAgentIds.Remove(agent);
return null;
}
public ViewResult BlankRow()
{
return View("AgentIdPartial", new BankListAgentId());
}
Followed this post and used the .live command.
$('#agentTable').live('click', 'tr a', function (e) {
$.ajax({
url: '#Url.Action("DeleteRow", "BankList")',
data: { id: $(this).attr('id') },
dataType: 'html',
cache: false,
context: this,
success: function () {
$(this).parents('tr').remove();
}
});
});