Refreshing a table without reloading a page in spring mvc using javascript - javascript

I am having a simple table which shows basic details about cusotmers. Each customer belongs to one of available customer groups. I also have a dropdown on the top of it where I can toggle between available customer groups and want to update the table with customers belonging to that particular group. Right now everything happens using page reload which is quite inefficient I know. Is there a way to use js here and make only the table section refresh without reloading the entire page.
#GetMapping(WebControllerConstants.RIDER_MAPPING)
public ModelAndView riderMapping(#RequestParam(value = "groupId", required = false) String groupId) {
String group = "1";
if (groupId != null) {
group = groupId;
}
ModelAndView model = new ModelAndView("riderGroupDetails");
model.addObject("list", riderService.findRiderByGroupId(group));
model.addObject("riderGroupList", riderGroupService.findAllGroups());
return model;
}
<select id="category" name="category" onchange="GetAllDetails(this.value);">
//some options here
</select>
<table class="table table-striped table-bordered zero-configuration dataTable">
<thead>
<tr>
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
<th>Mobile No</th>
</thead>
<tbody>
<c:set var="id" value="${1}" />
<c:forEach var="rider" items="${list}">
<tr>
<td>
<c:out value="${id}" />
</td>
<td>
<c:out value="${rider.firstname}" />
</td>
<td>
<c:out value="${rider.lastname}" />
</td>
<td>
<c:out value="${rider.mobile}" />
</td>
</tr>
<c:set var="id" value="${id + 1}" />
</c:forEach>
</tbody>
</table>
<script>
$(window).on(
'load',
function() {
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)')
.exec(window.location.search);
return (results !== null) ? results[1] || 0 : false;
}
if ($.urlParam('groupId') == false) {
} else {
var groupId = $.urlParam('groupId');
console.log('groupId ' + groupId);
$("#category").val(groupId);
}
});
function GetAllDetails(value) {
groupvalue = value;
console.log(groupvalue);
var url = "${context}/rider/mapping?groupId=" + value;
//AJAX works here to send a request but table doesn't refresh.
window.location = url;
}
</script>

//AJAX works here to send a request but table doesn't refresh.
Here your AJAX could listen to a response code. If the code says transaction happened correctly you could create a js function that updates the page info while not refreshing it. The new info can be handled from js from the begining or on the response you can pass the info to be updated and pass it to the redrawing function.
Example:
function updateDBService(request){
var dataStr = JSON.stringify(request);
var url = '/updateDBService';
$.ajax({
url: url,
contentType: "application/json",
data: dataStr,
type: "POST",
statusCode: {
403: function () {
},
404: function () {
},
500: function (data) {
}
},
//This is your response object (data), which you can use to update the onscreen info
success: function (data) {
redrawInfo();
},complete: function(data) {
}
});
}
For this I usually create a controller different from the views controller so I can handle response classes, request classes and all sorts of stuff. Here a controller that uses POST method would be required.
Hopefully this helps you!

Related

Editable bootstrap table then Insert data to MYSQL database

I'm trying to use an editable bootstrap table where in data can be inserted on the database. However, I find it difficult since I'm only new with this field. I can load the data from the database and edit the table field but I don't know how can I insert it on the database.
Below is my code for the table. For the <tbody, I used javascript and ajax to load the data from the database. Note that, it only loads the CATEGORY ID and DESCRIPTION. The AMOUNT must be inserted by the user.
<div id="table" class="table-editable">
<table class="table table-sm table-striped table-hover" id="tbl-fees">
<thead>
<tr>
<th>CATEGORY</th>
<th style="display:none">CATEGORY ID</th>
<th scope="col">DESCRIPTION</th>
<th scope="col" class="text-right">AMOUNT</th>
</tr>
</thead>
<tbody id= "fees_table"></tbody>
</table>
</div>
As per the resources online, it says that I can use contenteditable="true" for me to have an editable table.
<script>
function load_fees_list()
{
var sy_id=2;
$.ajax({
method:"GET",
url: "<?php echo site_url(); ?>Get-FCP/"+sy_id,
success: function(response){
$.each(response.fcp_data, function(key, value){
$('#fees_table').append('<tr>\
<td style="display:none">'+value["fc_desc"]+'</td>\
<td id="fc_id">'+value["fc_id"]+'</td>\
<td id="fcp_description">'+value["fcp_description"]+'</td>\
<td id="fmf_amount" class="text-right" contenteditable="true">'+0+'</td>\
</tr>');
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus);
console.log("Error: " + errorThrown);
}
});
}
</script>
I found a script online where it shows the output of the live table when button is clicked.
var $TABLE = $('#table');
var $BTN = $('#export-btn');
var $EXPORT = $('#export');
// A few jQuery helpers for exporting only
jQuery.fn.pop = [].pop;
jQuery.fn.shift = [].shift;
$BTN.click(function () {
var $rows = $TABLE.find('tr:not(:hidden)');
var headers = [];
var data = [];
// Get the headers (add special header logic here)
$($rows.shift()).find('th:not(:empty)').each(function () {
headers.push($(this).text().toLowerCase());
});
// Turn all existing rows into a loopable array
$rows.each(function () {
var $td = $(this).find('td');
var h = {};
// Use the headers from earlier to name our hash keys
headers.forEach(function (header, i) {
h[header] = $td.eq(i).text();
});
data.push(h); //adds new items to the end of an array
});
// Output the result
$EXPORT.text(JSON.stringify(data));
});
However, I can't insert it on the database. I'm planning of inserting the data in a new MySQL table in which it stores the description and amount. Can someone help me on how can I insert it?

How do I save List of Checkboxes with value as Id to a database?

I have lists of courses from different table displaying on the same view as shown below
I want a user to select the courses he wants to register by selecting the checkboxes.
How do I get the Id's of the courses selected, then pass to the controller to save to another table.
I have my HTML code as this
#model FlexSchool.Data.Models.ClassModelIndex
<tbody>
#foreach (var item in Model.AdmInstAssignCourses.Where(m => m.IsCompulsory == true))
{
<tr>
<td>
<input type="checkbox" class="checkBox" name="check" value="#item.AdmInstCourses.CourseId" />
</td>
<td> #Html.DisplayFor(modelItem => item.AdmInstCourses.CourseCode) </td>
<td> #Html.DisplayFor(modelItem => item.AdmInstCourses.CourseName)</td>
<td> #Html.DisplayFor(modelItem => item.AdmInstCourses.Units)</td>
</tr>
}
</tbody>
Where ClassModelIndex is a class of IEnumerable Classes which i used in displaying different tables to list.
My button goes thus <input type="submit" value="Register Courses" id="register" class="btn btn-rose" />
My script looks like this
<script>
$(document).ready(function () {
$("#register").click(function () {
var selectedIDs = [];
$('input[type=checkbox]').each(function () {
selectedIDs.push($(this).val());
});
$.ajax({
url = "/Course/RegisterCourse",
type = "POST",
data = JSON.stringify({ courseIDs: selectedIDs }),
contentType = "application/json; charset=utf-8",
dataType = "json",
success = function (data) {
alert(data);
},
error = function () {
alert("Error while registering courses!");
},
});
});
</script>
My Controller is
[HttpPost]
public async Task<ActionResult> RegisterCourse(List<string> courseIDs)
{
var user = HttpContext.Session.GetString(InstName);
if (user == null)
{
return RedirectToAction("Login", "Account");
}
foreach (string courseID in courseIDs)
{
AdmInstCourses obj = await _context.AdmInstCourses.FindAsync(courseID);
var mycourses = new CourseRegModel { CourseCode = obj.CourseCode, CourseTitle = obj.CourseName, CourseUnit = obj.Units};
_context.Add(mycourses);
}
await _context.SaveChangesAsync();
return RedirectToAction("MyCourses", "Course");
}
But when I run the code in debugging mode, I notice my courseIDs is not getting any list of string as Id. So it is either the script is not getting the checked boxes to pass to the controller.
What exactly am I doing wrong?
The issue is with the JavaScript Code. You have missed :checked.Use following code to get all checked values. And make sure no space between input[type="checkbox"] and :checked.
var selectedIDs = [];
$('input[type="checkbox"]:checked').each(function () {
// looping through each checkbox and storing values in array for checked ones.
selectedIDs .push($(this).val());
});
Please try below Ajax code :
var selectedIDs = [];
$('input[type=checkbox]').each(function () {
selectedIDs.push($(this).val());
});
$.ajax({
url : '/Course/RegisterCourse',
type : "POST",
data: JSON.stringify(selectedIDs),
contentType : "application/json; charset=utf-8",
dataType : "json",
success : function (data) {
alert(data);
},
error : function () {
alert("Error while registering courses!");
}
});
Directly pass json string(JSON.stringify(selectedIDs)) to server side , and in the controller method, use [FromBody] to get the values :
[HttpPost]
public async Task<ActionResult> RegisterCourse([FromBody]List<string> courseIDs)
{
}
First and foremost you can't put ids in checkbox value, because the value of checkbox can has true or false.
Try to use html.HiddenFieldFor(model => model.YourModel[i]) and replace foreach by for.

Update gridview inside a partialview modal

I am having problems rendering a gridview with pagination on a modal. Whenever I click other pages, it doesn't render the modal at all. Just text with formatting of the next page. For now, these are the only ones I can show but if you need to see a screenshot of the problem, or the controller, I will try to post it.
There is no problem on getting the pagination to working. The only thing is the view. I call the #modal-container using an action link from INDEX view, and then shows with a gridview data inside. The problem is that when I click the next page of the data, though it goes to the next page, it un-renders all css of the whole page. Just a stripped down formatted-text. How can I update only the gridview?
#Html.ActionLink("Transaction History", "TransactionHistory", "AccountBalance", new { accountID = item.AccountID, page = 1, pageSize = 15 },
htmlAttributes: new
{
onclick = "GetPlayersDetails('" + item.AccountID + "')",
data_target = "#modal-container",
data_toggle = "modal",
#class = "btn btn-xs btn-flat btn-warning"
}).If("AccountBalance", "TransactionHistory")
Here is the onclick AJAX code:
function GetPlayersDetails(accountID) {
console.log('asdasd');
$.ajax({
url: '#Url.Action("TransactionHistory")', //"/Player/GetPlayersByTeam",
dataType: "html",
data: { accountID: accountID },
type: "GET",
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
toastr.error(err.message);
console.log('error');
},
success: function (data) {
$('#qweqwe').html(data);
console.log('success');
}
});
}
Here is the partialview Modal:
<table id="qweqwe" class="table table-hover table-bordered table-striped text-sm ordertable">
<thead>
<tr>
<th width="35%">Transaction Date</th>
<th>Notes</th>
<th>Amount IN</th>
<th>Amount Out</th>
</tr>
</thead>
<tbody id="checkboxTable">
#foreach (var item in Model.History)
{
<tr id="tableRow" class="text-center">
<td><br />#Html.DisplayFor(modelItem => item.TransactionDate)</td>
<td><br />#Html.DisplayFor(modelItem => item.Notes)</td>
<td><br />#Html.DisplayFor(modelItem => item.AmountIn)</td>
<td><br />#Html.DisplayFor(modelItem => item.AmountOut)</td>
<td class="text-center actionTD hidden">
</td>
</tr>
}
</tbody>
</table>
This is the pager on the modal:
#Html.PagedListPager(Model.History, page => Url.Action("TransactionHistory",
new
{
accountID = ViewBag.accountID,
page = page
}),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new PagedListRenderOptions
{
DisplayPageCountAndCurrentLocation = true,
DisplayItemSliceAndTotal = true,
ItemSliceAndTotalFormat = "Total Records: {2}",
LinkToFirstPageFormat = "First",
LinkToPreviousPageFormat = "Previous",
LinkToNextPageFormat = "Next",
LinkToLastPageFormat = "Last"
},
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "Get",
UpdateTargetId = "qweqwe"
}))
This is the action from my controller:
public ActionResult TransactionHistory(int accountID, int? page)
{
page = page == null ? 1 : page;
DateTime startDate = Convert.ToDateTime("10-26-2018");
DateTime endDate = Convert.ToDateTime("10-29-2018");
var list = BankAccountManagementBusinessLogic.GetDataUpdate(accountID, startDate, endDate, (int)page, pageSize);
int totalRows = list.Count() > 0 ? (int)list.First().TotalRows : 0;
var mylist = new StaticPagedList<spGetAccountTransactionHistory_Result>(list, (int)page, pageSize, totalRows);
TransactionHistorySearchModel searchModel = new TransactionHistorySearchModel();
TransactionHistoryViewModel model = new TransactionHistoryViewModel(searchModel, mylist);
ViewBag.accountID = accountID;
return PartialView(model);
}
Now, these codes work. Displaying the modal and the gridview. The problem is that when going to the next page, the css of the whole page disappears, just a formatted text of the second page is showing. I am unable to find a solution for this yesterday, hoping for an input. Thanks

After Ajax call succeed, DataTables search box doesn't work

I'm working on a project that php, js, jquery, datatables are included.
I'm sending post call to a PHP page to change my table data, it's running successfully as you see. After this call, I can't use my DataTable search feature strangely. May be the error is about $(".gunlukgelir").load(" .gunlukgelir"); when Ajax call is succeed, I reflesh the tables with the .gunlukgelir class name.
Libraries:
https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css
https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js
https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js
https://code.jquery.com/jquery-3.3.1.min.js
my Ajax call:
$(function() {
$("#gelirgetir").click(function() {
var gelirtablosecimi = $("#select1").val();
if (gelirtablosecimi) {
$.ajax({
type: "POST",
url: "tabloyenile.php",
data: {
"gelirtablosecimi": gelirtablosecimi
},
success: function(result) {
$(".gunlukgelir").load(" .gunlukgelir");
//$(".gunlukgelir").load(window.location + " .gunlukgelir");
notifyUser('success', 'Başarılı!', 'Tablo başarıyla güncellendi');
},
error: function(result) {
notifyUser('error', 'Hata', 'error');
}
});
} else {
notifyUser('info', 'Dikkat', 'Tablo seçimi yapmadınız!');
}
});
HTML part:
<div class="form-group col-xs-6">
<select id="select1" class="selectpicker" data-live-search="true" title="Gelirler">
<?php echo $geliroptions;?>
</select>
<input type="submit" id="gelirgetir" value="Getir" class="btn btn-success" />
<h1>Aylık Gelir Raporları</h1>
<table id="" class="display table table-stripe table-hover table-row-border table-order-column table-nowrap gunlukgelir">
<thead>
<tr>
<th>Tarih</th>
<th>Günlük Toplam</th>
</tr>
</thead>
<?php
$gelirtabloadi = $_SESSION["gelirtabloadi"];
$gelirgunluktoplam = $db->prepare("select tarih, hasilat + visa + butce_ici + hisse_satis + sosyal_konut + elektrik + haberlesme + iller_bank + diger AS Toplam from $gelirtabloadi");
$gelirgunluktoplam->execute();
while($row = $gelirgunluktoplam->fetch()){
echo '
<tr>
<td>'.$row["tarih"].'</td>
<td>'.$row["Toplam"].'</td>
</tr>
';
}
?>
</table>
</div>
and PHP that Ajax calls:
<?php
session_start();
if($_POST['gelirtablosecimi'] && $_POST['gidertablosecimi']){
$gidertabloadi = $_POST["gidertablosecimi"];
$gelirtabloadi = $_POST["gelirtablosecimi"];
$_SESSION["gelirtabloadi"] = $gelirtabloadi;
$_SESSION["gidertabloadi"] = $gidertabloadi;
}
if($_POST["gelirtablosecimi"]){
$gelirtabloadi = $_POST["gelirtablosecimi"];
$_SESSION["gelirtabloadi"] = $gelirtabloadi;
}
if($_POST['gidertablosecimi']){
$gidertabloadi = $_POST["gidertablosecimi"];
$_SESSION["gidertabloadi"] = $gidertabloadi;
}
?>
Any suggestion? Thanks in advance!
I also had such a problem. Just add .DataTable() in success function of ajax after assigning the data to data table.
It has been working for me.
Just write it as follows:
function TaxLoad() {
$.ajax({
url:"myCode.php",
type:"POST",
data:{functionName:"showTax"},
success:function(data) {
$("#tblTaxBody").html(data);
var table= $("#dtTable").DataTable();
}
});
}`
Probably this issue related with my problem in the Docs. If It reinitialised, it would be searching: false Anyway, If one day anybody sees this problem, just change your table choice to Bootstrap-Table. It's much more stable.

How to get checkbox value and send that to backend?

This is front end,
<div class="uk-width-1-4 ">
<table class="uk-table uk-table-striped uk-table-hover" id="tabledata">
<thead>
<tr>
<th><input type="checkbox" ></th>
<th>Site ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" id="chkall" value="<%= d.siteid%>">
</td>
<td><%=d.siteid%></td>
</tr>
<% });
} %>
</tbody>
</table>
</div>
This is backend,
var user_id=req.query.user_id;
var siteid=req.query.chkall;
console.log("chkall =="+siteid);
sql="UPDATE site SET userid='"+user_id+"' WHERE siteid IN('"+siteid+"')";
}
getSQLData(sql, function(resultsets){
console.log("user...sql"+sql);
userresults = resultsets;
});
You can use it like this:
$("input[type='checkbox']").val();
Hope will help you.
If you are doing form submit, and if the check-box un-checked the false value will not go to the back-end. You should have some hidden value if check box un-checked.
If it is ajax call, you can get checkbox value as like below
$("input[type='checkbox']").val();
or
$("#checkboxid").val();
If you submit form then write name tag. And if you send data from ajax then get value by element id then send to server.
You do like this..
var chk = document.getElementById(checkboxid).checked;
if (chk == true) {
var chkval=$("#checkboxid").val();
}
If you have in list then do loop and add to a global variable and use that variable.
//check box
<asp:CheckBox ID="chkpermission" runat="server" onclick="checking(this.id);" Checked='<%# Convert.ToBoolean(Eval("permission")) %>' />
<script type="text/javascript">
function checking(id) {
$('#ctl00_ContentPlaceHolder1_lblresponce').val('');
if (id) {
ids = id.split('_');
var chkval = document.getElementById(id).checked;
var TitleId = "ctl00_ContentPlaceHolder1_grdpermissions_" + ids[3] + "_hdntitleid"; //here i am getting the value from the grid
var pagePath = window.location.pathname;
var param = JSON.stringify({ "TitleId": itleId,"chkval":chkval });
$.ajax({
type: "POST",
url: pagePath + "/updatevalue",
data: param,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != null) {
var result = data.d;
$('#ctl00_ContentPlaceHolder1_lblresponce').text('Updated successfully');
}
},
error: function () {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
}
}
</script>
in the back end code
[WebMethod]
public static Boolean updatevalue( string TitleId, string chkval)
{
Boolean flag = false;
if ( TitleId != "" && chkval !="")
{
//Update your your query here with single id...
flag=true;
// return flag if updated
}
return flag;
}
I hope it works in your case.

Categories

Resources