ASP.NET Programmatically inserting table rows from AJAX - javascript

I have a simple HTML table within a cshtml page. It is basically a single column, where I want to programmatically insert rows from the result of an ajax call.
<table class="table" id="notestedtable">
<tr>
<th>
Not Tested
</th>
</tr>
<tr>
<td>
Unit#1
</td>
</tr>
</table>
I use the document.onload = NotTested("Site 001", "17/06/2015"); to call the function which then executes the ajax.
function NotTested(SiteId,TestDate) {
$.ajax({
url: '/Home/NotTested',
type: 'POST',
contentType: 'application/json;',
data: JSON.stringify({
siteid: SiteId, testdate: TestDate
}),
success: function (result) {
for (var i = 0; i < result.Tubs.length; i++) {
alert(result.Tubs);
}
}
})
}
The returned Tubs is a string[] where Tubs[0] = "Tub 1"; Tubs[1] = "Tub 2" ... and so on. I want each of the Tub[] to form a row in my table.
This is the C# in the controller:
[HttpPost] // can be HttpGet
public ActionResult NotTested(string siteid, string testdate)
{
int i = 0;
//this could be populated first by reading for this "site" how many tubs to be expected
string[] UnTested = new string[8];
SqlConnection conn = new SqlConnection(#"Server=****;Database=****;User Id=****;Password=****;");
SqlCommand cmd = new SqlCommand("select * from TubsNotTested(#siteid,#testdate)", conn);
cmd.Parameters.AddWithValue("#siteid",siteid);
cmd.Parameters.AddWithValue("#testdate", testdate);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
for(i=0; i<dt.Rows.Count; i++)
{
UnTested[i] = dt.Rows[i][0].ToString();
}
return Json(new
{
Tubs = UnTested,
}, JsonRequestBehavior.AllowGet);
}

Modify the ajax success callback to
success: function (result) {
$.each(result.Tubs, function(index, item) {
var cell = $('<td></td>').text(item); // create the table cell
var row = $('<tr></tr>').append(cell); // create the table row
$('#notestedtable').append(row); // append the row to the table
});
}
Side note: It would be better to include var table=$('#notestedtable'); at the top of your script to cache the element and then use table.append(row); so avoid traversing the DOM again.

Try the following:
var table = document.getElementById("notestedtable");
for (var i = 0; i < result.Tubs.length; i++) {
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
cell.innerHTML = result.Tubs[i];
}

Related

How to update data in SQL for an html table row using Input Button, in JS or C#?

I have a datatable in C# and I am converting it to html table like below.
public static string ConvertDataTableToHTML(DataTable dt)
{
StringBuilder html = new StringBuilder();
html.Append("<table id='example' class='table table-striped table-bordered' cellspacing ='0' width ='100%' font size='8' aria-hidden='true'>");
//add header row
html.Append("<thead>");
html.Append("<tr>");
for (int i = 0; i < dt.Columns.Count; i++)
html.Append("<td>" + dt.Columns[i].ColumnName + "</td>");
html.Append("<td>" + "Action" + "</td>");
html.Append("</tr>");
html.Append("</thead>");
//add rows
for (int i = 0; i < dt.Rows.Count; i++)
{
html.Append("<tr>");
for (int j = 0; j < dt.Columns.Count; j++)
html.Append("<td>" + dt.Rows[i][j].ToString() + "</td>");
html.Append("<td><input type=\"button\" value=\"Delete\" onclick=\"deleteRow(this)\"/></td>");
html.Append("</tr>");
}
html.Append("</table>");
return html.ToString();
}
This is showing a table in my aspx page like below:
Name City Quantity Action
A X 5 Delete
B Y 10 Delete
C Z 15 Delete
When I click "Delete" button for a row, the function below works and the row is gone from the result table.
<script>
function deleteRow(btn)
{
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
</script>
What I want is that, in addition to the current process, I need to run a SQL query to update IsRemoved flag for this data in my SQL Server 2014 table.
The query I need to run: Update MyTable set IsRemoved=1 where Name='A' and City='X'
I could not manage to run it in JavaScript function, and could not find a way to execute another function in C# after the JS function. OnClientClick is not working since it is not an asp:Button, and when I try to use asp:Button instead of input element, it does not show it on the screen.
How can I change data in DB here for such an example? Please note that I am trying not to use a GridView. Any help would be appreciated.
EDIT: By using Ajax, how can I send paramaters from my ajax call to c#:
I am trying:
$.ajax({
type: 'POST',
url: 'mypage.aspx/DeleteRowFromDB',
data: JSON.stringify({ name: **<nameshouldcomehere>**, city:**<cityshouldcomehere>** }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
});
I can't find how to set name and city dynamically based on the row clicked the delete button, any tips?
In your .cs page create a WebMethod which will mark the Database entry as IsRemoved=1 as:
[System.Web.Services.WebMethod]
public static string DeleteRowFromDB(string name,string city)
{
var status = "0";
//Your code to mark `IsRemoved=1` for the selected entry goes here and set the `status` variable as status="1" if the DB command successed.
return status;
}
And then create a function with an ajax call to invoke the created WebMethod and remove the row from HTML if the status is true as:
function deleteRow(btn)
{
var row = btn.parentNode.parentNode;
var cells = row.getElementsByTagName("td");
var reqData = JSON.stringify({ name: cells[0].innerText, city:city=cells[1].innerText });
//now make a call to the `WebMethod` via `ajax`.
$.ajax({
type: 'POST',
url: 'mypage.aspx/DeleteRowFromDB',
contenttype: 'application/json; charset=utf-8',
data: reqData,
datatype: 'json',
success: function (response) {
if(response === "1") {
row.parentNode.removeChild(row);
}
else
{
//do other stuff
}
},
error: function (error) {
//handle the error
}
});
}
Note: if the response variable in the ajax success function doesn't have the desired value try to look for its response.d property value.

ASP.NET MVC ADO.NET Query per table row

Here I have this table:
If I click the button, I want to pass the table per row to the controller, then perform ADO.NET Query per row, like for example, perform "UPDATE tbluser SET note='INACTIVE' WHERE id=#id" per row.
One of the main purpose of this is when i filter the table, only the visible rows will be passed.
I already have a code here to pass to controller using AJAX but I don't know what to do afterwards.
JS:
var HTMLtbl =
{
getData: function (table) {
var data = [];
oTable.rows({ search: 'applied' }).every(function () {
var cols = [];
var rowNode = this.node();
$(rowNode).find("td").each(function () {
cols.push($(this).text().trim() || null);
});
data.push(cols);
});
return data;
}
}
$("btnSubmit").on("click", function () {
var data = HTMLtbl.getData($(".datatable"));
var parameters = {};
parameters.array = data;
var request = $.ajax({
async: true,
cache: false,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Home/SubmitTable",
data: JSON.stringify(parameters),
success: function () {
window.location.href = "/Home/Index";
}
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
Controller:
[HttpPost]
public JsonResult SubmitTable(string[][] array)
{
//I don't know what to do here now, please help
}
My Solution based on Mostafa's answer:
JS:
var HTMLtbl =
{
getData: function () {
var data = [];
oTable.rows({ search: 'applied' }).every(function () {
var cols = [];
var rowNode = this.node();
$(rowNode).find("td").each(function () {
cols.push($(this).text().trim() || null);
});
data.push(cols);
});
return data;
}
}
$("#btnSubmit").on("click", function () {
var data = HTMLtbl.getData($(".datatable"));
var parameters = {};
parameters.array = data;
var request = $.ajax({
async: true,
cache: false,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Home/SubmitTable",
data: JSON.stringify(parameters),
success: function () {
window.location.href = "/Home/Index";
}
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
Controller:
[HttpPost]
public JsonResult SubmitTable(string[][] array)
{
string result = string.Empty;
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
con.Open();
foreach (var arr in array)
{
SqlCommand cmd = new SqlCommand("UPDATE tbluser SET remark='INACTIVE' WHERE id = #id", con);
cmd.Parameters.AddWithValue("#id", arr[0]);
cmd.ExecuteNonQuery();
}
con.Close();
}
catch (Exception ex)
{
result = ex.Message;
}
return Json("Records updated successfully.", JsonRequestBehavior.AllowGet);
}
I can now use this for more complicated stuff, thanks
If you want to update a custom row you can add a button for each row with custom text and icon, then add a "data-" attribute to this button and path your row id,
<input type="button" data-rowId="1" class="changeActivationState">activate</input>
in this example I added a data field to my imput after that I define this javascript method:
$(".changeActivationState").click(function(){
$(this).data("rowId")//get the selected row id and call you service
});
using this code you can read first element for each row and perform a web service call for all rows
var arr = [];
$("#yourtable tr").each(function(){
arr.push($(this).find("td:first").text()); //put elements into array
});
and using this code you can read all rows into a json object
var tbl = $('#yourtable tr').map(function() {
return $(this).find('td').map(function() {
return $(this).html();
}).get();
}).get();
assume that you passed the list to action
int[] passedIDsfromBrowser = ///filled with data that comes from browser;
SqlConnection connection = ....
SqlCommand command = new SqlCommand(connection);
command.CommandText = "Update MYTABLENAME Set Active = true where ID in (" string.Join(",", passedIDsfromBrowser ) + ")";
connection.Open();
command.ExecuteNonQuery();
connection.Close();
this is a pseudo code.
or if you want a loop and updating each row with a loop
SqlConnection connection = ....
SqlCommand command = new SqlCommand(connection);
connection.Open();
for(int i = 0 ; i < passedIDsfromBrowser.Length; i++){
command.CommandText = "YOURQUERY";
command.ExecuteNonQuery();
}
connection.Close();

Html table row not appending to specified table

I am trying to add the json string to an html table. The object data is correct but it is not appending to the table. What am I doing wrong with my jquery append statement?
function GetSongs(id) {
$.ajax(
{
type: "Get",
url: "#Url.Action("GetSongs", "Game")",
data: { playlistId : id },
success: function (data) {
json = data;
obj = JSON.parse(json);
for (var i = 0; i < data.length; i++) {
$('#song-table').append('<tr>'+ htmlEncode(obj[i].SongURL) +'</tr>');
}
}
});
}
HTML Table:
<div id="player-playlist">
<table id="song-table" style="width:420px">
<tr>
<th>Song</th>
</tr>
<tr>
<td>http://www.youtube.com/v/CFF0mV24WCY</td>
</tr>
</table>
</div>
First try to debug the output what data you getting on ,is it a JSON string you returning from server side, also try to append td inside tr, and for htmlEncode write the custom function htmlEncode as shown below
function GetSongs(id) {
$.ajax(
{
type: "Get",
url: "#Url.Action("GetSongs", "Game")",
data: { playlistId : id },
success: function (data) {
console.log(data);
json = data;
obj = $.parseJSON(json);
for (var i = 0; i < data.length; i++) {
$('#song-table').append('<tr><td>'+ htmlEncode(obj[i].SongURL) +'</td></tr>');
}
}
});
}
function htmlEncode (value) {
if (value) {
return jQuery('<div />').text(value).html();
} else {
return '';
}
}
remove htmlEncode() because it is not defined in your js, define it or remove it
for (var i in obj) {
$("#song-table").append("<tr><td>"+ obj[i].SongURL +"</td></tr>");
}
OR
for (var i in obj) {
$("#song-table").append("<tr><td>"+ htmlEncode(obj[i].SongURL) +"</td></tr>");
}
function htmlEncode(string)
{
var pre = document.createElement('pre');
var text = document.createTextNode(string);
pre.appendChild(text);
return pre.innerHTML;
}//end htmlEncode it escapes HTML
You are trying to append it to <tr> rather than <td>. Change it to:
$('#song-table').append('<tr><td>'+ htmlEncode(obj[i].SongURL) +'</td></tr>');

How to prevent showing duplicate informations in the sequential time period

I wrote a method (with WebMethod attribute) which give me list of books :
public struct BOOK
{
public string BOOK_NAME;
public string BOOK_DESC;
}
[WebMethod]
public static List<BOOK> GetMyBooks()
{
string _connString = "Data Source=.;Initial Catalog=BookStore;Integrated Security=True";
SqlConnection _conn = new SqlConnection(_connString);
_conn.Open();
SqlCommand _com = new SqlCommand("select * from Book_TBL where IsActive='True' ", _conn);
_com.CommandType = System.Data.CommandType.Text;
SqlDataAdapter bookdataAdapter = new SqlDataAdapter(_com);
DataSet bookDS = new DataSet();
bookdataAdapter.Fill(bookDS, "Book_TBL");
List<BOOK> bookList = new List<BOOK>();
BOOK book;
foreach (DataRow dr in bookDS.Tables["Book_TBL"].Rows)
{
book = new BOOK();
book.BOOK_NAME = dr["book_name"].ToString();
book.BOOK_DESC = dr["book_desc"].ToString();
bookList.Add(book);
}
return bookList;
}
and i wrote a script that call the "GetMyBooks" method every 5 second and show it in a div tag by id:"pejiGrid" in my WebForm2.aspx :
<script>
$(document).ready(function () {
$("#go").click(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "WebForm2.aspx/GetMyBooks",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
for (var i = 0; i < response.d.length; i++) {
$("#pejiGrid").append("<tr><td>" + response.d[i].BOOK_NAME + "</td><td>" + response.d[i].BOOK_DESC + "</td></tr>");
}
}, });
}, 5000);
});
});
but my method and script append duplicate information in my "#pejiGrid", i want to show this information only once, is there any way,which i can do it by script? if it is not possible, what is the solution?
Everything in code is OK. You need just a small correction in your script. Replace the success function body with this code:
var htm = [];
for (var i = 0; i < response.d.length; i++) {
htm.push("" + response.d[i].BOOK_NAME + "" + response.d[i].BOOK_DESC + "");
}
$("#pejiGrid").html(htm.join(''));
If I correctly understood the question the problem was in using the 'append' method of jQuery, which was appending all new data received from server. Instead of that you were needed to replace old data with new one. So you need to use the 'html' method to replace the content of div.
One more advice. It will be better to store methods like 'GetMyBooks()' in web services files, developed specially for that purpose.
Wish you all the best !

Load table with updated data via ajax

I am developing a mobile app using Phonegap and jQuery Mobile. Basically for the first time when the app loads the data which gets populated using AJAX comes fine but It doesn't update.
Example: If there are 5 rows of data coming from the database and with some users action 1 more row has been added in the database but it still displays 5 rows. Currently it updates only if I exit app fully.
Also to solve this problem I have tried the following:
tbody.append(tableCells).load();
tbody.append(tableCells).trigger('create');
tbody.append(tableCells).trigger('refresh');
Any solution/idea how can I update it live or something without a user exits the app completely? Please see the below code.
Code:
HTML:
<table id="myPendingChallenges-table" width="100%">
<thead>
<tr>
<th>Game Type</th>
<th>Team Name</th>
<th>Initiator Name</th>
</tr>
</thead>
<tbody></tbody>
</table>
to append rows inside the
JS: tbody.append(tableCells);
AJAX:
var currentUser = window.localStorage.getItem("currentUser");
user = JSON.parse(currentUser);
var username = user.username; //User name
//alert (username+', '+t_name+', '+formAction);
$.ajax({
type: 'POST',
url: 'http://www.example.com/webservice/index.php',
data: {username: username},
dataType : 'json',
success: function(data){
var json = JSON.stringify(data);
window.localStorage.setItem("teamChallenges", json);
challengePopulate();
},
error: function(){
alert('error!');
}
});
return false;
function challengePopulate()
{
var json = window.localStorage.getItem("teamChallenges");
var data = null;
if(!json)
data = JSON.stringify(window.teamChallenges);
var data = JSON.parse(json);
if(!data)
return;
var fields = ["game_type", "t_name", "ini_name"];
populatePCTable("#myPendingChallenges-table", fields, data);
}//end challengePopulate
function populatePCDTable(tableId, fields, data)
{
var tbody = $(tableId + " tbody");
var row = null;
for(var i in data) {
row = data[i];
if(!row)
continue;
var tableCells = "";
var fieldName = "";
for(var j in fields){
fieldName = fields[j];
teamName = row[fields[1]];
gameParam = row[fields[3]];
if(row[fieldName] == 'weighin'){
game_type = 'weighin';
row[fieldName] = '<img src="images/weightGame.png" width="100%" />';
}else if (row[fieldName] == 'activity'){
game_type = 'activity';
row[fieldName] = '<img src="images/activityGame.png" width="100%" />';
}
tableCells += "<td onClick=\"setPendingChallTitle('"+teamName+"');pendingchallengeDetails('"+teamName+"');\"><a href='#pendingChallengesDetailsPage'>"+row[fieldName]+"</a></td>";
}
tbody.append("<tr>" + tableCells + "<td onClick=\"ignorePendingChallenge(this,'"+teamName+"');\"><a href=''><img src='images/close_button.png' title='Ignore Challenge' /></a></td></tr>");
}
}//end function populatePCDTable

Categories

Resources