How to edit table contents from another page using javascript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm looking to add a page to my website that will have a table that will display the products that are available.
What I would like to be able to do, is make it so that the contents of the table can be changed from another page (say an admin page). Is it possible to do something like this using JavaScript or something similar? If so can you please point me in the right direction.
Much appreciated thanks.

There are few ways.
Not involving server-side
You need a reference to the other window. You can get that e.g. by opening the window - window.open().
Then you use the HTML DOM methods, e.g. the document.getElementById(...) and then the specific element's API:
https://developer.mozilla.org/en/docs/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces
http://www.w3schools.com/jsref/dom_obj_table.asp
Involving server-side
This means that one page would send some data to the server and the other would read them.
You can use the AJAX concept for that - see the answer with XMLHttpRequest.
The other page would have to check periodically, or the first page would have to give it some signal - call some JavaScript method you wrote, or reload the window. Other option would be to use the push concept, but that's currently an advanced technique.

You could use XMLHttpRequest for this , but I would recommend that you use jQuery which would then be the $.ajax() function. What this does is send data to the server without refreshing the page or without anybody knowing about it really.
So what you could do is on the admin side is send some changes data to the server and on the client side unless you use a Web Socket you would have to contact the server every so many seconds to see if there are any changes. then the server would send you any changes that would have been made by the admin then you would work with that result with javascript to display changes on the web page.
What is Ajax
jQuery Ajax
Here is the requested example using jQuery
in your php you would have something like this
if($_POST['type'] === 'updateProduct') {
// update database with new price
// You could have a field in the database that now say's
// that the product has been updated
// send the response
echo 'done';
}
// And the admin ajax something like this
$.ajax({
type: 'POST',
url: 'linkToYourFile.php', // The php file that will process the request
data: {
type: 'updateProduct', // This is all the data you wan't to send to your php file
productID: 8484737,
newPrice: '$100.99'
},
success: function( result ) { // if we get a response
if(result === 'done') {
// The product has been updated from the admin side
}
}
});
// on the client side
if($_POST['type'] === 'checkForUpdates') {
// Contact the database and check that $_POST['productID']
// has been updated
// use php's json_encode function to echo the result
}
var checkForUpdates = function() {
$.ajax({
type: 'POST',
url: 'LinkToYourFile.php',
dataType: 'JSON',
data: {
type: 'checkForUpdates',
productId: 8484737
},
sucess: function ( result ) {
if( result.updated === true ) {
someElementPrice.textContent = result.newPrice;
}
}
});
};
window.setInterval(checkForUpdates, 3000); // Send's the update request every 3 seconds
Note - it's not easy to do this stuff if your not familiar with it. but you will learn.
Thats the fun part. and there is a lot more to it behind the scenes, but this is the idea of it

Possible solution
Using an AJAX call, you could store the table itself in an HTML file.
Here is an example page. If you have any questions, do not hesitate to ask them. I added a few functions such as Add Row.
LIVE DEMO
Admin management page (index.html)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery AJAX</title>
<link type="text/css" rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<style rel="stylesheet" type="text/css">
tr, td,th{
border-collapse: collapse;
border:1px solid;
}
td{
height:22px;
min-width:125px;
}
</style>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">"http://jquery.com"</script>
<script type="text/javascript">
/* ---------------------------------- */
/* See the SCRIPT part of this answer */
/* ---------------------------------- */
</script>
</head>
<body>
<h1>jQuery AJAX Table</h1>
<section>
<article>
<div id="myTable" contenteditable></div>
<nav data-type="table-tools">
<ul>
<li>
New row
</li>
<li>
New column
</li>
<li>
Save table
</li>
</ul>
</nav>
</article>
</section>
</body>
</html>
SCRIPT
/* On page load */
$(document).ready(function () {
var getTable = function () {
/*We empty the div */
$('#myTable').html('');
/*We load the table */
$.get('myTable.html', function (callback_data) {
var table = callback_data;
document.getElementById('myTable').innerHTML = table;
});
};
getTable();
/* ----- */
/* New row button */
$('#addRow').click(function (event) {
/* Prevents the real anchor click event (going to href link)*/
event.preventDefault();
/* We get the number of columns in a row*/
var colNumber = $($('#myTable tbody tr')[0]).children('td').length;
var tr = document.createElement('tr');
var td = "";
for (var i = 0; i < colNumber; i++) {
td = document.createElement('td');
td.appendChild(document.createTextNode("\n"));
tr.appendChild(td);
}
$('#myTable tbody').append(tr);
});
$('#addColumn').click(function (event) {
event.preventDefault();
$.each($('#myTable table thead tr'), function () {
$(this).append('<th></th>');
})
$.each($('#myTable table tbody tr'), function () {
$(this).append('<td></td>');
});
});
$('#saveTable').click(function (event) {
event.preventDefault();
var table = $('#myTable').html();
$.post('saveTable.php', {
'myTable': table
}, function (callback_data) {
console.log(callback_data);
$('#myTable').slideToggle('fast');
setTimeout(function () {
getTable();
$('#myTable').slideToggle();
}, 100);
});
});
});
saveTable.php
<?php
if(!isset($_POST['myTable']))
die('No data provided.');
$table = $_POST['myTable'];
$handle = fopen('myTable.html','w');
$result = fwrite($handle,$table);
if($result)
fclose($handle);
else
die('Error writing file');
?>
myTable.html
<table>
<thead>
<tr>
<th>Lorem ipsum dolor.</th>
<th>Velit, vero, quis.</th>
<th>Id, dolore, commodi!</th>
</tr>
</thead>
<tbody>
<tr>
<td>Lorem ipsum.</td>
<td>Voluptatibus, maiores.</td>
<td>Quod, et.</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Ex, assumenda!</td>
<td>Qui, pariatur!</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Alias, amet.</td>
<td>Delectus, itaque!</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Praesentium, quod.</td>
<td>Dolor, praesentium?</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Beatae, perferendis!</td>
<td>Voluptates, earum!</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Ratione, quis.</td>
<td>Cupiditate, repellendus.</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Porro, labore.</td>
<td>Eligendi, nemo!</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Soluta, suscipit.</td>
<td>Dolorem, dolores.</td>
</tr>
</tbody>
</table>

This is possible with some limitations:
You should change the table that displays the products, to fetch the values beeing displayed using ajax. Then you have 2 possibilities: (I'm pretty sure there are more but I only think of those 2 at the moment)
create a timer which will fetch the values for a product every X seconds
create a listener that will be called when a value in the db gets updated
This way you can change the values in an backend and the will be automatically updated in your frontend view.
You can have a look at the meteor framework where they use 'Live HTML' excessive.

Related

Onclick event open a new page and load an table by doing an api call using javascript

I'm trying to display a table on a new page by calling an API and loading the data in the table. This page is loaded on click of a menuItem.
But the issue I'm facing is that the table is displaying, but not the data I'm intending to. I know that I'm able to fetch the data from the API since i can see that in the console log.
Here is the code:
In this first html file im clickling the menu and calling my next html page i want to load
and also im giving my id="covidLink" which im calling in my JS FILE.
pan.html
<div class="navbar">
<a class="covidText" id="covidLink" href="covidStatusUpdate.html">Covid-19</a>
</div>
In the below js file im making a call to the api and appending the data in tbody.
Fetchdata.js
$(document).ready(function () {
$("#covidLink").click(function () {
console.log("Link clicked...");
requestVirusData();
});
});
function requestVirusData() {
$.getJSON('https://api.covid19api.com/summary',
function(data){
var countries_list = data.Countries;
//console.log(countries_list);
$(countries_list).each(function(i, country_dtls){
$('#totalbody').append($("<tr>")
.append($("<td>").append(country_dtls.country))
.append($("<td>").append(country_dtls.TotalConfirmed))
.append($("<td>").append(country_dtls.TotalDeaths))
.append($("<td>").append(country_dtls.TotalRecovered)));
});
})
}
and lastly
statusUpdate.html
<table class="table table-striped table-bordered table-sm" cellspacing="0" width=80%>
<thead>
<tr>
<th>Country</th>
<th>TotalConfirmed</th>
<th>TotalDeaths</th>
<th>TotalRecovered</th>
</tr>
</thead>
<tbody id="totalbody">
</tbody>
</table>
What am I supposed to do ? I have to admit that I'm lost here.
I don't think you quite understand how AJAX works. You're handling a click on "covidLink". This does two things simultaneously.
it tells the browser to navigate away from the current page and go to statusUpdate.html instead.
it runs the requestVirusData() function. This gets the data from the API and returns it to the page.
But the problem is: the API call returns the data to the page where the script was called from - i.e. it returns it to pan.html. And you've just told the browser to move away from that page. Also, pan.html doesn't contain a table to put the returned data into.
The logical solution here is to link to fetchdata.js from statusUpdate.html instead, and tweak the code slightly so it runs when that page loads, rather than on the click of a button:
$(document).ready(function () {
console.log("page loaded...");
requestVirusData();
});
As suggested by ADyson i did changes in my code and now im able to display the table with data.
Here are my code changes:
statusUpdate.html
<tbody id="tbody">
<script>
var datatable;
fetch('https://api.covid19api.com/summary')
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
console.log('error: ' + err);
});
function appendData(data) {
var countries_list = data.Countries;
var tbody = document.getElementById("tbody");
// clear the table for updating
$('table tbody').empty();
// hide the table for hidden initialize
$('table').hide();
// loop over every country
for (var i in countries_list) {
var country_dtls = countries_list[i];
// replace -1 with unknown
for (var o in country_dtls) {
if (country_dtls[o] == -1) country_dtls[o] = 'Unknown';
}
$('table tbody').append(`
<tr>
<td>${country_dtls.Country}</td>
<td>${country_dtls.TotalConfirmed}</td>
<td>${country_dtls.TotalDeaths}</td>
<td>${country_dtls.TotalRecovered}</td>
</tr>`);
}
}
// }
</script>
</tbody>
pan.html
<a class="covid" href="statusUpdate.html">Covid-19</a>
and now i do not need fetchdata.js obviously.
Hope this helps someone stuck like me :)

hide table header column

I use jquery code to pull results for a search query on my website. I would like to hide one of the table's column headers when the results appear. I have made the appropriate changes in HTML and the table appears correct when I go directly to the search results page, but if I refresh the search results page or pull a new query from that page, the table reverts back to the original text.
My question is, how do I adjust the jquery code to hide the column header text from appearing everytime it refreshes?
Here is the jquery I am using
jQuery('.loading').show();
var dataArr = {'region_id': region_id, 'from_date': from_date, 'to_date': to_date, 'course_no': course_no, 'course_id': course_id, 'gtr': gtr};
jQuery.ajax({
url: Drupal.settings.basePath + "course/search/region/api",
type: 'post',
cache: false,
datatype: 'json',
data: dataArr,
success: function (result) {
jQuery('.loading').hide();
var parsed = JSON.parse(result);
//jQuery('.result_search_region').html(result.data);
if (parsed.data.length > 0) {
jQuery('.result_search_region').html(' ');
jQuery('.result_search_region').append('<h5>Course Availability</h5>');
jQuery('.result_search_region').append(parsed.data);
} else {
jQuery('.result_search_region').html(jQuery('#dt_no_schedule').html());
}
}
});
Here is the html I am using:
<?php
$schedule_in_arr = Direction_Session::get('schedule_id');
$data_by_time = Direction_Session::get('data_by_time', array());
?>
<?php if (!empty($value['schedule_info'])): ?>
<table class="jz-table jz-table-bordered jz-table-striped">
<caption><?php echo $value['location_name']; ?></caption>
<?php if (!empty($value['schedule_info'])): ?>
<thead>
<tr>
<td>Start Date</td>
<td class="alncenter">Duration</td>
<td class="alncenter">Time</td>
class="alncenter"></td>
<td class="alncenter"></td>
</tr>
</thead>
<tbody>
It seems a little unclear do want to remove the head once you get the data (might be a poor user experience), or are you getting multiple headers shown?
To hide the thead figure out where/when you want to hide the header with this:
var elem = $("thead");
elem.css('visibility', 'hidden');
Or if you keep getting multiple:
table
thead
thead
...
Then I'd suggest the DOM node you're updating/replacing isn't correct. I'd suggest you look at replacing the tbody alone on update and get remove the thead in the html your graft in. One thing about the code, as someone that needs to test stuff alot, where are the ID's on your elements, make everyone's life easier.... :)

How to fetch data from file using ajax on clicking table rows

I am trying to fetch the data from files using Ajax by clicking row of table (passing row values to button on clicking rows) or by entering the variables in text box and pressing button. But it does not seem to be working.(Pls don't downvote as i am C++ programmer and learning web development.)
<!DOCTYPE html>
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script>
<table bodrder=1 class='list'>
<thead>
<tr>
<th class='A'>ID</th>
<th class='B'>Value</th>
<th class='C'>Name</th>
<th class='D'>Cell #</th>
<th class='E'>Nickname</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>54235</td>
<td>Benjamin Lloyd</td>
<td>(801) 123-456</td>
<td>Ben</td>
</tr>
<tr>
<td>2</td>
<td>44235</td>
<td>XXXXXX</td>
<td>642363673</td>
<td>TRE</td>
</tr>
</tbody>
</table>
<div id="tabs" class="plots-tabs" style="padding-top: 10px; padding-bottom: 10px">
<table>
<tr><td>ID:<input id="id" type="text" class="inputbox" /></td></tr>
<tr><td>Value:<input id="value" type="text" class="inputbox" /></td></tr>
</table>
This is DIV element which will be filled by div element on clicking button or by clicking table row which also generate the event and click the button by passing values to ajax and fetchign data.
<p style="width: 100%; text-align: right;"><button type="button" id="button">Submit</button></p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
//here ID and value are parsed through table click event or from text box on clicking button
$.ajax({
url:filename,
data: {
ID: $("input#id").val(),
Value: $("input#value").val()
},
success:function(result){
$("#tabs").html(result);
}});
var filename= "Data_"+ID+"_"+Value+".txt";
$("#tabs").load(filename);
});
});
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
for (var i = 0; i < 2; i++) {
data.push(cells[i].innerHTML);
}
}
alert(data);
};
</script>
</body>
</html>
cat Data_2_54235.txt
Nice Work! Your code is working with first file.
cat Data_2_44235.txt
Nice Work! Your code is working with second file.
how can i implement the above code.
I see you generate a filename based on input values. That means that the ajax call will be made upon that filename, which is odd, becouse you have to create a file with that name.
Anyway, i don't see nowhere in your code that by clicking table rows you make an ajax call, you only save the innerHTML text to a variable data = [] and then alert it. But the problem is not here (if you don't expect to make ajax call when clicking table-rows), but it is inside the ajax call you are making when clicking the button.
first
url:filename
var filename= "Data_"+ID+"_"+Value+".txt";
I strongly suggest you don't do that. It will work if you make an ajax call to a php script which creates that txt file with filename name, and then make another ajax call to that file and fetch it.
second
data: {
ID: $("input#id").val(),
Value: $("input#value").val()
}
look here at data, the doc explains it. the code above means that to filename it will pass parameters (GET parameters, i.e. x?=...), but becouse your file is .txt, this doesn't make sense.
third
$("#tabs").load("demo_test.txt");
This will add the text inside demo_test.txt to $("#tabs") , like innerHTML does or .html() does. Do you have demo_test.txt on your host? i suppose this should work.
just change you ajax call and load call with this. this should work :
$("button").click(function() {
$.ajax({
url : "demo_test.txt",
dataType: "text",
success : function (data) {
$("#tabs").html(data);
}
});
});
For clicking the table-rows, just add an event listener to table-rows, and make an ajax call. read the link i send you, as they are important to understand better what is ajax.
You can see no unnecessary data parameter is thrown to ajax call, and i put there an dataType, meaning that we expect text data to be recieved. If this doesn't work, you have to be sure that you are working on localhost server(for ajax to work...) and you have demo_test.txt , and the url is passed correctly
example using input values to fetch from ajax:
$("button").click(function() {
var id = $("input#id").val();
var value = $("input#value").val();
$.ajax({
url : "Data_" + id + "_" + value + ".txt",
dataType: "text",
success : function (data) {
$("#tabs").html(data);
},
error: function (data) {
#("#tabs").html('No such file found on server');
}
});
});
example of event handler click <tr>
$("table tbody").on("click", "tr", function() {
var id = $(this).find("td")[0].text(); // gets the first td of the clicked tr (this is the ID i suppose)
var value = $(this).find("td")[1].text(); // gets the second td of the clicked tr (this is the VALUE i suppose)
$.ajax({
url : "Data_" + id + "_" + value + ".txt",
dataType: "text",
success : function (data) {
$("#tabs").html(data);
},
error: function (data) {
#("#tabs").html('No such file found on server');
}
});
});

How to do SQL write in document that is largely javaScript and JQuery

I'm trying to figure out how to get a SQL DB write into my file that is largely javaScript and JQuery. I've found some php info online, but I'm having trouble getting the php into my code with everything else that's there. I'm trying to utilize an array where I put user entered info from an html table, and call a method that uses the array as a parameter. I have made my entire file a php file, but I'm having trouble figuring out where to put the php <?php ?> delimeters without having my bigTableRows array go out of scope, or other run-time error messages. After I figure this out I need to do a MS SQL write. Right now, I see this error message, but no table. Line 83 is the line after the <?php, where I have echo(bigTableRows[0];
Parse error: syntax error, unexpected '[' in E:\visE\jqproject\web\BigTable.php on line 83
If I take away the [0] part, I get a syntaxError, but see the table ok:
missing; before statement.
This is what it looks like:
BigTable.php:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>
<meta content="utf-8" http-equiv="encoding"/>
<title>Big Table</title>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript">
//Used to make row editable or not
$(document).ready(function () {
$('.editbtn').click(function () {
var currentTD = $(this).parents('tr').find('td');
if ($(this).html() === 'Edit') {
$.each(currentTD, function () {
$(this).prop('contenteditable', true);
});
} else {
$.each(currentTD, function () {
$(this).prop('contenteditable', false);
});
}
//change button text when hit it between edit/save
$(this).html($(this).html() === 'Edit' ? 'Save' : 'Edit');
var bigTableRows = getBigTableRowData(0); //first row
console.log("bigTableRows other", bigTableRows);
InsertData(bigTableRows);
});
function InsertData($theDataArr)
{
//The php part below isn't working**********************
$bandY = $theDataArr[0];//$_POST['bandY'];
$bandM = $theDataArr[1];//$_POST['bandM'];
$bandC = $theDataArr[2];//$_POST['bandC'];
$bandK = $theDataArr[3];//$_POST['bandK'];
$comment = $theDataArr[4];//$_REQUEST['comment'];
console.log("bandY php: ", $bandY);
console.log("bandM php: ", $bandM);
console.log("bandC php: ", $bandC);
console.log("bandK php: ", $bandK);
console.log("comment php: ", $comment);
<?php //where to put this and still have variable info******
echo(bigTableRows[0]);
//console.log("bandY php: ", $bandY);
//console.log("bandM php: ", $bandM);
//console.log("bandC php: ", $bandC);
//SQL dB write to follow after I can access data**************
?>
}
});
</script>
<script>
function getBigTableRowData(rowNum)
{
//I just need row data for the one that was just edited/saved******
var rowText = $("#bigTable tbody tr:eq(" + rowNum + ") td").map(function() {
// Find all of the table cells on this row.
// Determine the cell's row text
return $(this).text();
}).get();
return rowText;
}
</script>
</head>
<body>
<div class="form">
<p>
<h1> Visual Evaluation Entry Table </h1>
</p>
</div>
<table id="bigTable" border="1">
<thead>
<tr>
<th id="edit" class="col3">Edit/Save</th><th id="bandY" class="col3">Bands #263mm Y</th><th id="bandM" class="col3">Bands #263mm M</th><th id="bandC" class="col3">Bands #263mm C</th><th id="bandK" class="col3">Bands #263mm K</th><th id="Comments" class="col3">Comments</th></tr>
</thead>
<tbody>
<tr>
<td><button class="editbtn">Edit</button></td>
<td name="bandY" contenteditable="false"></td> <!-- //Row 0 Column 1-->
<td name="bandM" contenteditable="false"></td> <!--//Row 0 Column 2-->
<td name="bandC" contenteditable="false"></td> <!--//Row 0 Column 3-->
<td name="bandK" contenteditable="false"></td> <!--//Row 0 Column 4-->
<td name="comment" contenteditable="false"></td> <!--//Row 0 Column 4-->
</tr>
</tbody>
</table>
</body>
</html>
Some examples I've found are:
php sql write,
and
put html table data into array
I know that if I take away the <?php delimeters, it would run ok (minus echo) (and access the array data), but I need them to do the php part. If I'm off-base on any of this, which I'm sure something is, feel free to let me know. I have a little php experience with xml/html, but I'm learning javaScript and JQuery, and I've never tried to put it all together before.
OK, im really trying to be constructive here, i never used the Microsoft SQL connector on PHP but looking on the documentacion is very similar to the MySQL connector (i think is meant to be that way).
So, you need to create the connection first, if your doing it, you need to iterate the dataset to obtain data or pass the data to an array.
In your example code i see a mix of JS with PHP, that's just not right.
the only thing you need to do is read this link: this link!
1.- Create the connection.
2.- run the query.
3.- fetch the dataset to an array (this is only my personal recomendation).
4.- Use the data inside the PHP or save it on a variable like this.
<?php
echo "var val = " . $myArray[0][0] . ";"; /** Here you are "printing" the variable declaration into the HTML document. **/
?>
In fact, if you want your data on JSON to be used in a javascript object, you can do it this way.
<?php
echo "var myObj = '" . json_encode($myArray) . "';";
?>
If i missed something let me know.

Adding table rows from a Grails Template on Button Click

So, the _form.gsp template associated with my create.gsp creates an initial table from a template for the row as follows:
<table id="myTable">
<!-- define table headers here -->
<g:each var="i" in="${1..5}">
<g:render template="tableRow" model="['i': i]" />
</g:each>
</table>
What I'd like to do is add a button or a link underneath that table that let's you add five more rows, while keeping all the data you've entered in the form so far.
I can see how that's possible in "pure" javascript, but I'd basically have to repeat the _myTable.gsp HTML in my javascript file. I'd like to avoid that (DRY, etc.).
How can I do that?
Edit
So, I tried Gregg's solution (below). Here's what I came up with.
The Controller has an action:
def addMoreRows() {
println params
def i = params.rowNumber + 1
def j = i+5
println "i is set to " + i
render(template: "foapRow", bean:i, var:i, model: ['rowStart': i, 'rowEnd': j])
}
The create.gsp page calls the _form.gsp as normal, adding a rowStart and a rowEnd to the model.
create.gsp
<g:render template="form" model="['userId':userId, 'rowStart':1, 'rowEnd':5]"/>
*_form.gsp*, in turn, passes those parameters on to the row template, and creates a link to call the above controller action. It also has the javascript Gregg recommended:
<script type="text/javascript">
$("#addRowsLink").on("click", function(e) {
e.preventDefault();
$.get("/Controller/addMoreRows", function(html) {
$("#theTableInQuestion>tbody").append(html);
});
});
</script>
<table>
...
<g:render template="tableRow" model="['rowStart':1, 'rowEnd':5]"/>
</table>
<g:remoteLink id="addRowsLink" action="addMoreRows" update="theTableInQuestion" onSuccess="addRows(#theTableInQuestion, data, textStatus)" params="['rowNumber':data]">Add More Rows</g:remoteLink>
The *_tableRow.gsp* begins and ends with:
<g:each var="i" in="${rowStart..rowEnd}">
<tr>
...
</tr>
</g:each>
From a previous attempt, I have this function in my included javascript file:
function addRows(tableId, rowCode, status) {
$(tableId + ' tr:last').after(rowCode);
}
Right now, when I click the "Add More Rows" link, I still get taken to a new page, and it only has one row on it.
One possible solution. You're going to need to change your template so it does the looping:
GSP:
<table id="myTable">
<tbody>
<g:render template="tableRows" model="[loopCount:loopCount, moreData:moreData]" />
</tbody>
</table>
Template:
<g:each in="${loopCount}" var="idx">
<tr>
<td>.....</td>
......
</tr>
</g:each>
JavaScript:
$("#someButtonId").on("click", function(e) {
e.preventDefault();
$.get("/controller/someAction", function(html) {
$("#myTable>tbody").append(html);
});
});
Controller:
def someAction = {
// logic here
render template: "tableRows", model="[loopCount: 5, moreData:moreData]"
}
You could also submit all the data in your table to the server every time and refresh the entire page, adding logic to loop over some variable number of rows. But you would need to collect all that data on the server and make sure it gets put back in the request.
There's probably a dozen ways to do this so don't be surprised if you get that many answers. :o)

Categories