I have an html page and I need to send the contents of a table in a POST.
How do I capture the content of the table using jQuery and pass it to the server (which is running node.js and express.js)?
This is the example of a table in a page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="scripts/jquery-3.2.1.min.js"></script>
</head>
<body>
<table id=horarios>
<tr>
<td>1 </td>
<td>2 </td>
<td>3 </td>
</tr>
<tr>
<td>4 </td>
<td>5 </td>
<td>6 </td>
</tr>
</table>
<form method=post>
<input type="submit" value="Save">
</form>
</body>
</html>
In the server I would capture that POST with something like:
var bodyParser = require('body-parser');
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded({ extended: true }));
app.post('/mypage', function(req, res){
var content = req.body;
res.render('somepage');
});
You want to send a POST request with body set to $('#horarios').html()
You can do this with jQuery.post()
$.post(url, data, success, respType)
where data is the html string of your table, success is a callback if the server sends a success response, and resType is the type of data your server should send back (i.e. text, html, xml, json, script)
So for your example, try adding this inside a script tag on your html page:
// bind to form submit
$('form').submit(function(){
// get table html
var table = {html: $('#horarios').html()};
// POST the data
$.post('/mypage', table, function(response, textStatus){
// do anything with the response here ...
})
});
You need to convert your table into a data structure. You can achieve this with:
var tbl = $('#horarios tr').map(function(rowIdx, row) {
var rowObj = $(row).find('td').map(function(cellIdx, cell) {
var retVal = {};
retVal['cell' + cellIdx] = cell.textContent.trim();
return retVal;
}).get();
var retVal = {};
retVal['row' + rowIdx] = rowObj;
return retVal;
}).get();
In this way you will pass the table as an array of rows of cells.
$('input[value="Save"]').on('click', function(e) {
//
// prevent form submit
//
e.preventDefault();
//
// collect table data by row X col
//
var tbl = $('#horarios tr').map(function(rowIdx, row) {
var rowObj = $(row).find('td').map(function(cellIdx, cell) {
var retVal = {};
retVal['cell' + cellIdx] = cell.textContent.trim();
return retVal;
}).get();
var retVal = {};
retVal['row' + rowIdx] = rowObj;
return retVal;
}).get();
console.log('-->' + JSON.stringify({table: tbl}));
$.post('/mypage', {table: tbl}, function(data, textStatus, jqXHR) {
console.log('success');
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id=horarios>
<tr>
<td>1 </td>
<td>2 </td>
<td>3 </td>
</tr>
<tr>
<td>4 </td>
<td>5 </td>
<td>6 </td>
</tr>
</table>
<form method=post>
<input type="submit" value="Save">
</form>
If you want the data to send via post, first you have to extract values from the table and i recommend you put it into an array, then send it via ajax post.
$('form').on('submit', function(e) {
e.preventDefault();
var $dataElements = $('#horarios').find('td'),
data = [];
$.each($dataElements, function(i, elem){
data.push($(elem).html());
});
$.ajax({url:'/mypage', method: 'POST', data: {data:JSON.stringify(data)}});
});
In other hand if you only want to send the html just send it using $('#horarios').html() instead of loop through elements and add it to the post data.
I hope it helps...
Related
I'm trying to populate my bootstrap table (in Database.Master) with data (in DatabaseUI.aspx.cs).
How do I dynamically add rows to the table with Jquery?
Do I have to convert my string to JSON?
I think I have to add another JQuery script in the masterpagefile to append data to the table
$(function() {
$.each(response, function(i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.UID)
.appendTo('#lblDatabase');
});});
but I'm not sure how to pass to get response in the script to read the string in DatabaseUI.
In Database.Master
<form id="form1" runat="server">
<table class="table" id="lblDatabase">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Pid</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
<asp:Label ID="lblDatabaseValues" runat="server"></asp:Label>
</td>
</tr>
</tbody>
</table>
</form>
Code that gets data from API in DatabaseUI
protected async void GetRequest(string url)
{
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(url))
{
using (HttpContent content = response.Content)
{
Label lblDatabaseValues = (Label)Master.FindControl("lblDatabaseValues");
//lblDatabaseValues.Text = "Values:";
//lblDatabaseValues.Text = "";
string myContent = await content.ReadAsStringAsync();
string[] values = myContent.Split(';');
for (int i = 0; i < values.Length; i++)
{
lblDatabaseValues.Text = lblDatabaseValues.Text + Environment.NewLine + values[i];
}
lblDatabaseValues.Text = lblDatabaseValues.Text.ToString().Replace(Environment.NewLine, "<br />");
}
//response.IsSuccessStatusCode
//response.StatusCode
}
}
}
Basically the question is not much clear. If you are asking about how to loop over the received response from backend and append it to your table then here is the code for you.
<table id="tdUIDs">
</table>
var rows = "";
$.each(response,function(i,item){
rows += "<tr><td>" + item.UID + "</td></tr>"; //your rows get printed here
});
$("#tdUIDs").append(rows);
I hope this is what you are asking for as am not clear with your question.
I'm trying to send an array via ajax so I have the following code:
Here is the code
function fncGetChecksToProcess() {
var allChecks = [];
$('input[type=text]').each(function() {
var key = $(this).attr("id").replace("txt_", "");
allChecks[key] = [];
});
$('input[type=checkbox]').each(function() {
if (this.checked) {
var className = $(this).attr('class');
if (className.includes('box_total_')) {
var ref = $(this).attr('id').replace("box_total_", "");
var amountDetails = [];
var docNs = [];
$('.' + ref).each(function() {
amountDetails.push(parseFloat($(this).closest('td').next().html().replace("$", "").replace(",", "")));
docNs.push($(this).attr('id').replace("box_", ""));
});
allChecks[ref].push({
docN: docNs,
amountTot: $("#sub_" + ref).text(),
amountDetails: amountDetails,
chkNum: $("#txt_" + ref).val()
});
} else {
var docN = $(this).attr('id').replace("box_", "");
allChecks[className].push({
docN: docN,
amountTot: $("#td_" + docN).text(),
amountDetails: "",
chkNum: $("#txt_" + className).val()
});
}
}
});
return allChecks;
}
$(document).ready(function() {
$("#btn").click(function() {
var checks = fncGetChecksToProcess();
console.log(checks);
$.ajax({
cache: false,
type: 'POST',
data: {
allChecks: checks
},
url: '/process',
beforeSend: function() {
console.log("Processing your checks please wait...");
},
success: function(response) {
console.log(response);
},
error: function() {
console.log("Error");
}
});
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="app.js"></script>
</head>
<body>
<table id="table" class="tablesorter" width="100%" cellspacing="0">
<thead>
<tr>
<th>H1</th>
<th>H2</th>
<th>H3</th>
<th>H4</th>
<th>H5</th>
<th></th>
<th>H6</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>11002WR</td>
<td>201100</td>
<td>A</td>
<td class="center"><input class="11002WR" id="box_201100" type="checkbox" /></td>
<td id="td_201100">$320.00</td>
</tr>
<tr>
<td colspan="3"></td>
<td>Check. No</td>
<td><input id="txt_11002WR" type="text"></td>
<td><input id="box_total_11002WR" class="box_total_201100" type="checkbox" /></td>
<td id="sub_11002WR">$12.00</td>
</tbody>
</table>
<input id="btn" type="button" value="Test" />
</body>
</html>
Please check the two checkboxes and the input and press on the test.
The console prints out the array generated but Ajax does not send it.
Why my ajax call does not send any parameters? I don't see them in chrome console.
Thanks.
Since your keys are strings, not numbers, you should be using an object, not an array. Change
var allChecks = [];
to
var allChecks = {};
When you send an array with $.ajax, it only sends the elements with numeric indexes, not named properties.
You need to send an array to ajax , now you send an array of array inside array...
if you post to the server like form the post will looks like:
allchecks[] = x
allchecks[] = y ...
https://plnkr.co/edit/SnZmKgRLODYb8p6kPryn?p=preview
$.ajax({
cache: false,
type: 'POST',
data: {
allChecks: checks["11002WR"][0]
},
this is a fast solution for you . but it is not a good practice
instead of allchecks=[] . try to build objects with keys or ids and not string like the ref as a key of the array
objects is like the following :
var allChecks = {};
I am using script to print selected values from table into another div.
<script>
$(".addValues").click(function () {
$('#selection').show();
var $this = $(this),
myCol = $this.closest("td"),
myRow = myCol.closest("tr"),
targetArea = $("#selection");
var qte_input = ('<input type="text" name="kolicina" id="kolicina" placeholder="kg / m" size="10"/>');
var broj = ($("td.data-id", myRow).text());
targetArea.prepend(broj + qte_input +"<hr />");
var arr = { sifra:broj, kolicina:qte_input };
$.ajax({
url: 'script.php',
data: arr,
type: 'post',
});
});
</script>
I am trying to get selected values in script.php, multiple values will be selected and after each selection I need to type quantity that is var qte_input.
Could anyone tell me how to set var broj as input and in the same time print it to another div as selected?
html code
<table id="datatable" class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>-</th>
</tr>
</thead>
<tbody>
<?php while($r=$q->fetch()){ ?>
<tr>
<td class='data-id'><?=''. $r['Id']?> </td>
<td> <button class="addValues" value="<?=''. $r['Id']?>"><i class="ion-ios-cart-outline"></button></td>
</tr>
<?php } ?>
</tbody>
</table>
Once I click on button one value prints in div. Multiple values could be selected as displayed on the image. Once I finish selection I hit button "Pošalji zahtjev" it should pick up all
You should write a function which collect you all data from the table. After that this collection should be sent to you backend via ajax. Demo in this fiddle: https://jsfiddle.net/mgrem9gb/
/**
* Function collect the form data
*/
function collectData(container){
var data = [];
$(container).find('tbody').find('tr').each(function(index, item){
var rowData = {
id: $(item).find('td.data-id').text(),
value: $(item).find('input[name="kolicina"]').val()
};
data.push(rowData);
});
return data;
}
/**
* Excecute the data collect function and the ajax post
*/
$.ajax({
url: 'script.php',
data: collectData('#datatable'),
type: 'post',
});
I have a table where in I have binded the values which are coming from the Form.In that form I have a primary key Field as TicketId which I have kept as hidden in the form and while inserting it into the table I am showing it.For Binding the data I have used Knockout.So I want to delete the row that I will select.So while selecting it I should get the id of that row so that I can passed it to the Delete action using ajax.But My problem is that I am not getting that id.So how to do this?
My code:
<table id="table2" style="border: double">
<thead>
<tr>
<td>Ticket ID</td>
<td>Ticket Type</td>
<td>No of Tickets</td>
<td>Ticket Price</td>
<td>Start Date</td>
<td>End Date</td>
<td>Action</td>
</tr>
</thead>
<!--Iterate through an observableArray using foreach-->
<tbody id="ticketid" data-bind="foreach:TicketDatas">
<tr style="border: solid" data-bind="click: $root.getselectedTicket" id="updtr">
<td id="rowid" data-bind="text:TicketId">#*<span data-bind="text:No_Of_Ticket"></span>*#</td>
<td data-bind="text:SelectedTicketType">#*<span data-bind="text:No_Of_Ticket"></span>*#</td>
<td data-bind="text:No_Of_Ticket">#*<span data-bind="text:No_Of_Ticket"></span>*#</td>
<td data-bind="text:Ticket_Price">#*<span data-bind="text:Ticket_Price"></span>*#</td>
<td data-bind="text:Start_Date">#*<span data-bind="text:Start_Date"></span>*#</td>
<td data-bind="text:End_Date">#*<span data-bind="text:End_Date"></span>*#</td>
<td>
<button data-bind="click: $root.deleterec">Delete</button></td>
</tr>
</tbody>
</table>
<script type="text/javasript">
self.deleterec = function () {
if (confirm('Are you sure to Delete this ticket ??')) {
var tickid = $("#table2 tr:eq(0)").attr("id");
$.ajax({
type: "POST",
data: { id: tickid },
url: "Ticket/DeleteTicket",
//data: "{id:" + ko.toJSON(id) + "}",
success: function (data) {
self.TicketDatas.remove(data);
alert("Record Deleted Successfully");
//GetTickets();//Refresh the Table
},
error: function (error) {
alert(error.status + "<--and--> " + error.statusText);
}
});
}
};
</script>
so just want the solution for this statement if I ask in short
var tickid = $("#table2 tr:eq(0)").attr("id");
I'm not sure how the rest of your code goes, but here's the jQuery parts when you have a reference to the DOM node for the delete link.
I assigned most parts to variable names to be more descriptive here, but you can make this more concise for your use.
$('#table2 .delete-link').click(function() {
var deleteLink = $(this);
var tableRow = deleteLink.closest('tr');
var firstCell = tableRow.find('td:first-child');
var ticketId = firstCell.attr('id');
// ... Do what you need to do with the ticket ID.
return false;
});
Additional References:
CSS pseudo-class :first-child
jQuery click()
jQuery closest()
jQuery find()
var tickid = $("#table2 tr:eq(0)").html();
OR
var tickid = $("#table2 tr:eq(0)").val();
I've done some code in html and in JavaScript ... My query is when I click on <td>, whatever the value associated with it, has to be displayed in the corresponding text box ...
In front of <td> I've taken the textbox ... for an example I've taken 3 <td> and 3 textboxes
<script type="text/javascript">
function click3(x) {
x = document.getElementById("name").innerHTML
var a = document.getElementById("txt");
a.value = x;
}
function click1(y) {
y = document.getElementById("addr").innerHTML
var b = document.getElementById("txt1");
b.value = y;
}
function click2(z) {
z = document.getElementById("email").innerHTML
var c = document.getElementById("txt2");
c.value = z;
}
</script>
this is my JavaScript code , I know this is not an adequate way to deal such problem, since its giving static way to deal with this problem
does anyone have a better solution for this problem ??
In JavaScript/jQuery
If click1, click2 and click3 are supposed to be three event then you have to keep all three function you can shorted the script code for assigning values to text field.
<script type="text/javascript">
function click3(x) {
document.getElementById("txt").value = document.getElementById("name").innerHTML;
}
function click1(y) {
document.getElementById("txt1").value = document.getElementById("addr").innerHTML;
}
function click2(z) {
document.getElementById("txt2").value = document.getElementById("email").innerHTML;
}
</script>
You can make a single function if you have single click event and shorten the code for assignment like this,
function SomeClick(x) {
document.getElementById("txt").value = document.getElementById("name").innerHTML;
document.getElementById("txt1").value = document.getElementById("addr").innerHTML;
document.getElementById("txt2").value = document.getElementById("email").innerHTML;
}
As far as I understood your question, you could try the following, assuming that's how your HTML is structured:
HTML Markup:
<table id="mytable">
<tr>
<th>Name</th>
<th>Address</th>
<th>Email</th>
</tr>
<tr>
<td class="name">Tom</td>
<td class="addr">789</td>
<td class="email">tom#dot.com</td>
</tr>
<tr>
<td class="name">Dick</td>
<td class="addr">456</td>
<td class="email">dick#dot.com</td>
</tr>
<tr>
<td class="name">Harry</td>
<td class="addr">123</td>
<td class="email">harry#dot.com</td>
</tr>
</table>
<input id="txt1" type="text" />
<input id="txt2" type="text" />
<input id="txt3" type="text" />
jQuery:
$(".name").click(function(){
$("#txt1").val($(this).text());
$("#txt2").val($(this).nextAll().eq(0).text());
$("#txt3").val($(this).nextAll().eq(1).text());
});
$(".addr").click(function(){
$("#txt2").val($(this).text());
$("#txt1").val($(this).prevAll().eq(0).text());
$("#txt3").val($(this).nextAll().eq(0).text());
});
$(".email").click(function(){
$("#txt3").val($(this).text());
$("#txt2").val($(this).prevAll().eq(0).text());
$("#txt1").val($(this).prevAll().eq(1).text());
});
DEMO: http://jsfiddle.net/Z9weS/
You can combine columns and rows. Per cell consisting id you give it th column title and
number of series it could be the index of the row combination of row and column gives the
address as per table cell by a specific event you can read the value of the id
Then you know to pull the cell value.
$('tr')
.click(function() {
ROW = $(this)
.attr('id');
$('#display_Colume_Raw')
.html(COLUME + ROW);
$('#input' + COLUME + ROW)
.show();
STATUS = $("#input" + COLUME + ROW)
.val();
});