Refresh HTML(JSP view) table after AJAX request - javascript

I have an HTML table which is populated in my JSP view. This table always contains data of the default today date. The data is retrieved by an automatic batch that fetch data from a database. However i have to give a functionnality to be able to select data on a daterange. This is why I use a daterangepicker. I succeeded to apply to datefilter with ajax calls.
What I want to do is to now when I select a new DateRange i update my already HTML table with the default date with Data from the selected date to replace the old data with new data in my table
Here is my JSP page with the table i want to update when i Select a DATERANGE:
<div class="panel-body">
<table width="100%"class="table table-striped table-bordered table-hover" id="tableUp">
<thead>
<tr>
<th>FormName</th>
<th>Type</th>
<th>Language</th>
<th>Sent To NAS</th>
<th>Sending Date</th>
<th>FeedBack Received</th>
<th>Feedback not Received</th>
</tr>
</thead>
<tbody id='tbod'>
<tr class="odd gradeX" id="myTable">
<c:forEach var="item" items="${eblinb2b_list}">
<tr id=1>
<td><c:out value="${item.form_name}" /></td>
<td><c:out value="${item.mode}" /></td>
<td><c:out value="${item.language}" /></td>
<td><c:out value="${item.count}" /></td>
<td><c:out value="${item.sendingDate}" /></td>
<td><c:out value="" /></td>
<td><c:out value="" /></td>
</tr>
</c:forEach>
</tr>
</tbody>
</table>
</div>
For the purpose of understanding a put here a new table in the lower part of my JSP view so that you understand:
<!-- DateRange PICKER -->
<div class="panel-body">
<table width="100%" class="class2" id="mainTable">
<thead>
<tr>
<th>FormName</th>
<th>Type</th>
<th>Language</th>
<th>Sent To NAS</th>
<th>Sending Date</th>
<th>FeedBack Received</th>
<th>Feedback not Received</th>
</tr>
</thead>
<tbody>
<tr class="odd gradeX" id="myTable1"></tr>
</tbody>
</table>
<input type="text" name="datepickerinput" id="datepicker" value="" />
</div>
<!-- /.panel-body -->
<button onclick="filterByDate()" id="button">Apply filter</button>
Here is my JavaScript function part that populate my second table for illustrating
**//Function for populating second table with Ajax JSON response**
var table = $("#mainTable tbody");
$.each(data, function(idx, elem) {
var time = new Date(elem.sendingDate);
var parsedTime = time.getDate() + "/" + (time.getMonth() + 1) + "/"
+ time.getFullYear();
table.append("<tr><td>" + elem.form_name + "</td><td>"
+ elem.mode + "</td><td>" + elem.language
+ "</td><td>" + elem.count + "</td><td>"
+ parsedTime + "</td></tr>");

I finally succeeded to manage the problem this is my final function that updates the table by putting the data and replacing the old one:
function prepareTable(data) {
//Function for populating table with Ajax JSON response
var table = $("#tableUp #tbody1");
var html = "";
$.each(data, function(idx, elem) {
var time = new Date(elem.sendingDate);
var parsedTime = time.getDate() + "/"
+ (time.getMonth() + 1) + "/"
+ time.getFullYear();
html += "<tr><td>" + elem.form_name + "</td><td>"
+ elem.mode + "</td><td>" + elem.language
+ "</td><td>" + elem.count + "</td><td>"
+ parsedTime + "</td><td></td><td></td></tr>";
});
table.html(html);
}
The prepareTable() function is triggered (called) when the Ajax call succeeded:
function filterByDate() {
var startDate = document.getElementById("datepicker").value
.substring(0, 10);
var endDate = document.getElementById("datepicker").value
.substring(13, 23);
$.ajax({
url : '/gms/eblinb2b/filterOnDate',
data : {
"startDate" : startDate,
"endDate" : endDate
}, //here you send the daterange over an Ajax request and by default it's sended with a GET method
success : function(data) {
//here you will see displaying the callback result coming from your spring controller
console.log(data);
//Here we populate the HTML table with the new data based on the new daterange filter applied and replace the old data in my table
prepareTable(data);
},
error : function(xhr, ajaxOptions, thrownError) {
if (xhr.status == 404) {
alert(thrownError);
}
}
});
}

Related

How can I delete all the columns in the Dynamic DataTable?

First, I want to delete all the columns and then use the select command to bring all the columns back for perform the refresh operation on the DataTable without refreshing page. So I need a piece of code that I can delete all the columns.
I shared my html and javascript code as shown following.
Can someone help me about this regard?
//CSHTML
<table id="datatables" class="table table-striped table-no-bordered table-bigboy" cellspacing="0" style="width:100%;">
<thead>
<tr>
<th class="disabled-sorting">Room Plan</th>
<th>Name</th>
<th class="disabled-sorting text-right">Actions</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Room Plan</th>
<th>Name</th>
<th class="text-right">Actions</th>
</tr>
</tfoot>
<tbody id="colmn">
#* *#
</tbody>
</table>
//*********************************JS*********************************//
//-------------------------SELECT ROOM START----------------------------
$.post("/Home/selectRooms", {}, function (data) {
var ndx = 0;
$.each(data.xroom_name, function (key, value) {
var Xroom_name = data.xroom_name[ndx];
var Xroom_plan = data.xroom_plan[ndx];
var column =
('<tr>' +
'<td>' +
'<div class="img-container">' +
'<img src="../../assets/img/room-plan/' + Xroom_plan + '" alt="..." id="imgsrc">' +
'</div>' +
'</td>' +
'<td id="imgname">' + Xroom_name + '</td>' +
'<td class="text-right">' +
'<i class="fa fa-edit"></i>' +
'</i>' +
'</td>' +
'</tr>');
document.getElementById('colmn').innerHTML = document.getElementById('colmn').innerHTML + column;
ndx++;
});
});
I also delete the column information that I clicked like this:
var table = $('#datatables').DataTable();
table.on('click', '.remove', function (e) {
$tr = $(this).closest('tr');
table.row($tr).remove().draw();
e.preventDefault();
});
I want to delete all columns because of I can refresh the table immediately after adding, updating and deleting. I do not want to delete the column that I clicked only.

Multiple ajax request is made to fill table rows. How to sort the table columns?

I am making multiple ajax request using JQuery to populate table rows. How to sort the table column. I am using the first API to fetch all symbol's value. The second API is used to find the values of that particular symbol. These values are appended into table. I want to use sorting on columns of the table.
tablesorter() is is a function which sorts table is not working. This is working fine for a simple table.
Here is my code.
<script type="text/javascript">
// HTTPRequest
var value = [];
$.ajax({
method: "GET",
url: "https://api.binance.com/api/v1/exchangeInfo"
})
.done(function(data){
data.symbols.forEach(function(element, index) {
value[index] = element.symbol;
$(".tablefriendsname").append("<tr><td>" + element.symbol + "</td></tr>");
$.ajax({
method: "GET",
url: "https://api.binance.com/api/v1/ticker/24hr?symbol=" + data.symbols[index].symbol
})
.done(function(data2){
$(".tablefriendsname2").append("<tr><td>" + data2.priceChange + "</td></tr>");
$(".priceChangePercent").append("<tr><td>" + data2.priceChangePercent + "</td></tr>");
$(".weightedAvgPrice").append("<tr><td>" + data2.weightedAvgPrice + "</td></tr>");
$(".prevClosePrice").append("<tr><td>" + data2.prevClosePrice + "</td></tr>");
$(".lastPrice").append("<tr><td>" + data2.lastPrice + "</td></tr>");
$(".lastQty").append("<tr><td>" + data2.lastQty + "</td></tr>");
$(".bidPrice").append("<tr><td>" + data2.bidPrice + "</td></tr>");
$(".bidQty").append("<tr><td>" + data2.bidQty + "</td></tr>");
$(".askPrice").append("<tr><td>" + data2.askPrice + "</td></tr>");
$(".askQty").append("<tr><td>" + data2.askQty + "</td></tr>");
$(".openPrice").append("<tr><td>" + data2.openPrice + "</td></tr>");
$(".highPrice").append("<tr><td>" + data2.highPrice + "</td></tr>");
$(".lowPrice").append("<tr><td>" + data2.lowPrice + "</td></tr>");
$(".volume").append("<tr><td>" + data2.volume + "</td></tr>");
$(".quoteVolume").append("<tr><td>" + data2.quoteVolume + "</td></tr>");
$(".openTime").append("<tr><td>" + data2.openTime + "</td></tr>");
$(".closeTime").append("<tr><td>" + data2.closeTime + "</td></tr>");
$(".firstId").append("<tr><td>" + data2.firstId + "</td></tr>");
$(".lastId").append("<tr><td>" + data2.lastId + "</td></tr>");
$(".count").append("<tr><td>" + data2.count + "</td></tr>");
$('#myTable').trigger('update');
}) // closed Inner done
}) // CLOSE FOREACh
}); // CLOSE outer DONE
<!-- Sorting Columns -->
$(document).ready(function()
{
$("#myTable").tablesorter();
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.29.5/js/jquery.tablesorter.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Crypto Api Fetch</title>
</head>
<body>
<table id="myTable" class="tablesorter">
<thead>
<tr>
<th class="">symbol</th>
<th class="">priceChangePercent</th>
<th class="">weightedAvgPrice</th>
<th class="">prevClosePrice</th>
<th class="">lastPrice</th>
<th class="">lastQty</th>
<th class="">bidPrice</th>
<th class="">bidQty</th>
<th class="">askPrice</th>
<th class="">askQty</th>
<th class="">openPrice</th>
<th class="">highPrice</th>
<th class="">lowPrice</th>
<th class="">volume</th>
<th class="">quoteVolume</th>
<th class="">openTime</th>
<th class="">closeTime</th>
<th class="">firstId</th>
<th class="">lastId</th>
<th class="">count</th>
</tr>
</thead>
<tbody>
<tr class="">
<td class="tablefriendsname"></td>
<td class="tablefriendsname2"></td>
<td class="priceChangePercent"></td>
<td class="weightedAvgPrice"></td>
<td class="prevClosePrice"></td>
<td class="lastPrice"></td>
<td class="lastQty"></td>
<td class="bidPrice"></td>
<td class="bidQty"></td>
<td class="askPrice"></td>
<td class="askQty"></td>
<td class="openPrice"></td>
<td class="highPrice"></td>
<td class="lowPrice"></td>
<td class="volume"></td>
<td class="quoteVolume"></td>
<td class="openTime"></td>
<td class="closeTime"></td>
<td class="firstId"></td>
<td class="lastId"></td>
<td class="count"></td>
</tr>
</tbody>
</table>
</body>
</html>
Load jQuery first.
Don't append a row into a cell; create a row string, add each cell, then append it to the table:
.done(function(data2){
var tr = '<tr><td class="symbol">' + element.symbol + '</td>';
// array of each table column in order
['priceChangePercent', ..., 'count'].forEach(item => {
tr += '<td class="' + item + '">' + data2[item] + '</td>';
});
$('#mytable).append(tr).trigger('update');
});

Trying to bind column dynamically in a table using jquery

I am trying to bind column dynamically in a table using jQuery .but click event is not working while trying to click 'btnASizeR' and 'btnWdDelete' button event is not working .Any idea would be appreciated.
$(function() {
var i = 0;
$('#btnASizeR').click(function() {
/* To check the count of already exist tr in WireDimTbl and then assigning the i value for controlids*/
var i = $("#WireDimTbl tbody>tr").length + 1;
/* To check the count of already exist tr in WireDimTbl and then assigning the i value for controlids*/
var sizerangeMin = "<input type='text' ID='SizeMin" + i + "' name='SizeMin' value='2.00' />";
var sizerangeMax = "<input type='text' ID='SizeMax" + i + "' name='SizeMax' value='3.00' />";
var ToleranceMin = "<input type='text' ID='TolMin" + i + "' name='TolMin' value='1' />";
var ToleranceMax = "<input type='text' ID='TolMax" + i + "' name='TolMax' value='1' />";
var markup = "<tr><td>" + sizerangeMin + "</td><td>" + sizerangeMax + "</td><td>" + ToleranceMin + "</td><td>" + ToleranceMax + "</td></tr>";
$("#WireDimTbl tbody").append(markup);
});
$('#btnWdDelete').click(function() {
$("#WireDimTbl tbody>tr:last").remove();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td class='text-left'><strong>Wire Dimensions</strong></td>
</tr>
<tr>
<td class='text-left'><strong>Standard Sizes & Tolerances</strong></td>
<td>
<input type="button" id="btnASizeR" value="AddSizeRange" />
<input type="button" id="btnWdDelete" value="Delete" />
<table id="WireDimTbl" class="table table-bordered">
<thead>
<tr>
<th class="text-center">Size Range Min (mm)</th>
<th class="text-center">Size Range Max (mm)</th>
<th class="text-center">Tolerance (-)mm</th>
<th class="text-center">Tolerance (+) mm</th>
</tr>
</thead>
<tbody></tbody>
</table>
</td>
</tr>
You mentioned that you are loading the table dynamically. Do you mean that when the page first loads the table is missing and its added later?
If that is the case, are you sure the code is called that binds the click events? The above example binds the events on page_load however, if the buttons are not yet available on the page it won't be able to bind it. JQuery will not automatically bind future elements.
Try settings a console.log($('#btnASizeR')); before binding the click event to make sure that JQuery can actually find the button.

using dynamic table to fill data only and pass the values to code behind ASP.NET

It's been a long time since I coded so I am facing troubles.
I am using VS2015 .NET c# webForms Application. I have a simple form where the user need to fill a dynamic table and after hitting submit the values are passed to code behind for some calculation then stored in DB.
I used the HTML table in the link http://talkerscode.com/webtricks/add-edit-and-delete-rows-from-table-dynamically-using-javascript.php
the output:
I cant use Gridview becuase it postsback and connects to DB directly. I dont want to store the input of the table immediately.
I am stuck at retrieving the data from HTML table.
Can I get some hints or suggest to me any other better way to do if any.
If you want I can provide the code.
Thanks
UPDATE:
my code
form.aspx
<form runat="server">
//elements here
<div class="table-responsive" id="div_invlv">
<!------TABLE ---->
<table id="data_table" class="table" >
<tr>
<th></th>
<th> </th>
<th>Name</th>
<th>Position</th>
<th>Company</th>
<th></th>
</tr>
<tr>
<td>
<select class="form-control" id="type_of_person">
<option>Internal</option>
<option>External</option>
</select> </td>
<td><input type="text" class="form-control" id="new_name" /></td>
<td><input type="text" class="form-control" id="new_position" /></td>
<td><input type="text" class="form-control" id="new_company" /></td>
<td><input type="button" class="btn btn-small btn-template-main add" onclick="add_row();" value="Add Row" /></td>
</tr>
</table>
</form>
Table.js
function delete_row(no)
{
document.getElementById("row"+no+"").outerHTML="";
}
function add_row()
{
var drop = document.getElementById("type_of_person");
var new_type = drop.options[drop.selectedIndex].innerHTML;
var new_name=document.getElementById("new_name").value;
var new_country=document.getElementById("new_position").value;
var new_company=document.getElementById("new_company").value;
var table = document.getElementById("data_table");
var table_len = (table.rows.length) - 1;
var row = table.insertRow(table_len).outerHTML = "<tr id='row" + table_len + "'><td id='id_row" + table_len + "'><asp:Label Name='id" + table_len + "' runat='server' > " + table_len + "</asp:Label></td> <td id='Type_row" + table_len + "'><asp:Label ID='type" + table_len + "' runat='server' > " + new_type + "</asp:Label></td><td id='name_row" + table_len + "'> <asp:Label ID='name'"+table_len+" runat='server' >" + new_name + "</asp:Label></td><td id='position_row" + table_len + "'>" + new_country + "</asp:Label></td><td id='company_row" + table_len + "'><asp:Label ID='company'"+table_len+" runat='server' >" + new_company + "</asp:Label></td><td > <input type='button' value='Delete' class='btn btn-small btn-template-main delete' onclick='delete_row(" + table_len + ")'></td></tr>";
document.getElementById("new_name").value="";
document.getElementById("new_position").value = "";
document.getElementById("new_company").value = "";
}
C#
string typeTable = Request.Form["type" + 1];
Label10.Text = typeTable ;
The rows are generated during the run and I am trying to retrieve the value of one cell in the first row for testing but its not working.
The link provided by #legends
https://www.aspsnippets.com/Articles/Dynamically-Add-Rows-to-GridView-using-JavaScript-on-Button-Click-in-ASPNet.aspx
works great and solved most of my issue.
Thanks
you can use this function to fill your datagrid dyamically
public void fillgrid(string qry, GridView dg){
try
{
sql.cmd = new SqlCommand("qry", sql.cn);
sql.cn.Open();
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(sql.cmd);
sda.Fill(ds);
dg.DataSource = ds;
dg.DataBind();
sql.cn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
or you can use a placeholder control to create a dyamic html table

AngularJS tags doesn't work in innerHTML

In my code i've a table which is populated by ng-repeat tag., and that's ok. By clicking a button, a row is added to this table by innerHTML. This new row should contain 2 cells:
select
input-field + a confirm button
I want to populate the select with ng-option tag, and this is not going to happend.
The angularJS tags (and whatever script or function i try to insert) grafted with innerHTML do not work.
methods is a JSON containing 3 payment methods (PayPal, Postepay, Skrill).
payment_methods contains the user payment methods (method + notes).
If i try to add the innerHTML code simply in the html page, it all works, so there's no bug in http requests or angularJS tags.
Any solution? Thanks.
$http.get('/api/v1/getUserPaymentMethods', {params: {"idUser": myService.get()}}).success(function (data) {
$scope.payment_methods = data;
});
document.getElementById('insert-btn').onclick = function () {
var table = document.getElementById('table');
var row = table.insertRow(table.length);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML =
"<select ng-model=\"selectedMethod\" " +
"ng-options=\"method.method for method in methods\">" +
"<option value=\"\" disabled selected>Method</option>" +
"</select>";
cell2.innerHTML =
"<div class=\"input-field\" style=\"display:inline-block; width: 87%\">" +
"<input type=\"text\" ng-model=\"notes\" id=\"notes\">" +
"</div>" +
"<div style=\"display:inline-block; width: 10%\"> " +
"<button id=\"confirm-btn\">done</button>" +
"</div>";
$http.get('/api/v1/getMethods').success(function (data) {
$scope.methods = data;
});
}
}
document.getElementById('confirm-btn').onclick = function () {
// save data
}
HTML:
<table id="table">
<thead>
<tr>
<th style="width: 30%;" data-field="id_payment_method">Method</th>
<th data-field="notes">Notes</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="payment_method in payment_methods">
<td>{{payment_method.id_payment_method}}</td>
<td>{{payment_method.notes}}</td>
</tr>
</tbody>
<div style="bottom: 50px; right: 50px;">
<button id="insert-btn">add payment method</button>
</div>
With Angular you don't have to build html manually, but do something like this:
<table id="table">
<thead>
<tr>
<th style="width: 30%;" data-field="id_payment_method">Method</th>
<th data-field="notes">Notes</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="payment_method in payment_methods">
<td>{{payment_method.id_payment_method}}</td>
<td>{{payment_method.notes}}</td>
</tr>
<tr>
<td>
<select ng-model="selectedMethod" ng-options="method.method for method in methods" >
</select>
</td>
<td>
<input type="text" ng-model="notes" id="notes"/>
</td>
</tr>
</tbody>

Categories

Resources