how to insert generated html table data into database in php? - javascript

How I can insert all data from a generated HTML table into my database using PHP?
I have tried with a foreach loop, but it gives me an error all the time.
I have this code in JavaScript to adding a new row using a button:
var i=1;
function addRow()
{
var tbl = document.getElementById('table1');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var firstCell = row.insertCell(0);
var el = document.createElement('input');
el.type = 'text';
el.name = 'to' + i;
el.id = 'to' + i;
el.size = 40;
firstCell.appendChild(el);
var secondCell = row.insertCell(1);
var el2 = document.createElement('input');
el2.type = 'text';
el2.name = 'cost' + i;
el2.id = 'cost' + i;
el2.size = 40;
secondCell.appendChild(el2);
frm.h.value=i;
i++;
}
And this is my HTML code:
<table id="table1" width="40%" border="2" cellpadding="0" cellspacing="0">
<tr>
<td><strong>To Address</strong></td>
<td><strong>Delivery Cost</strong></td>
</tr>
<tr>
<td><input name="to" type="text" id="to" size="40"/></td>
<td><input name="cost" type="text" id="cost" size="40"/></td>
</tr>
</table>
<br/><br/>
<input style="float: right;background-color: #57a000;height: 30px;font-weight: bold; font-family: cursive;margin-left: 10px;"
type="submit" value="Save All" name="SaveCost"/>
<input style="float: right;background-color: #57a000;height: 30px;font-weight: bold; font-family: cursive;"
type="button" value="Add New Place" onclick="addRow();"/>
<input name="h" type="hidden" id="h" value="0"/>
Finally I want to write some PHP to insert all the data from the generated HTML table into my database.

Related

Validate dynamic textbox length

I have a dynamic table which contains multiple textboxes. I need textbox B to have a maximum of 6 number input and will prompt an error if the input value is less than and not equal to 6. Please help Im new to javascript
function addRow() {
var table = document.getElementById("bod");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = '<input type="text" name="A" size="20" maxlength="6" required/>';
row.insertCell(1).innerHTML = '<input type="text" name="B" size="20" required/>';
row.insertCell(2).innerHTML = '<input type="text" name="C" size="20" required/>';
}
<input type="button" id="add" value="Add" onclick="Javascript:addRow()">
<table id="bod">
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</table>
Create input manually and addEventListener to it. Something like this.
function addRow() {
var table = document.getElementById("bod");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = '<input type="text" name="A" size="20" maxlength="6" required/>';
var colB = row.insertCell(1);
var inp = document.createElement('input');
inp.type = 'text';
inp.name = 'B';
inp.size = 20;
inp.required = true;
colB.appendChild(inp);
inp.addEventListener('change', function() {
if (this.value.length !== 6) {
alert('wrong value');
this.focus();
}
});
row.insertCell(2).innerHTML = '<input type="text" name="C" size="20" required/>';
}
<input type="button" id="add" value="Add" onclick="addRow()">
<table id="bod">
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</table>

Adding buttons to each row of a table to remove said row

just looking for a simple solution on solving this, Consider the the following code:
<!DOCTYPE html>
<html>
<head>
<title>Javascript - Add HTML Table Row </title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<form>
<script>
function addRow()
{
// get input values
var name = document.getElementById('name').value;
var currentAge =
document.getElementById('currentAge').value;
var Birthday = document.getElementById('Birthday').value;
var carType = document.getElementById('carType').value;
var Delete = document.getElementById('Delete').value;
var table = document.getElementsByTagName('table')[0];
var newRow = table.insertRow(table.rows.length/2+1);
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
var cel4 = newRow.insertCell(3);
var cel5 = newRow.insertCell(4);
cel1.innerHTML = name;
cel2.innerHTML = currentAge;
cel3.innerHTML = Birthday;
cel4.innerHTML = carType;
cel5.innerHTML = Delete;
function myFunction(){
var x = document.getElementById("table").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + " tr
elements in the table.";
}
</script>
</form>
</head>
<style>
table, th {
border: 1px solid black;
}
tbody td{
padding: 30px;
}
tbody tr:nth-child(odd){
background-color: #F4BC01;
color: #ABC412;
}
$("")
</style>
<body>
<h2>Basic HTML table</h2> <button onclick="myFunction()">Press me for
elements amount</button>
<p id ="demo"></p>
Name: <input type="text" name="name" id="name" /><br/><br/>
Age: <input type="text" name="currentAge" id="currentAge" /><br/><br/>
Date of Birth <input type="date" name="Birthday" id="Birthday" /><br/>
<button onclick="addRow();">Display</button><br/><br/>
<p>Eye Colour:</p>
<select id="carType">
<option value="ferrari" id="ferrari">Ferrari</option>
<option value="lamborghini" id="lamborghini">Lamborghini</option>
<option value="porsche" id="porsche">Porsche</option>
<option value="bugatti" id="bugatti">Bugatti</option>
<option value="pagani" id="pagani">Pagani</option>
</select>
<table border="1" id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Birthday</th>
<th>CarType</th>
<th>Delete Entry
<button id="Delete" onclick="remove_update(event)">delete</button> //this button right here but in each row and not here. should remove said row
</th>
</tr>
</table>
</body>
</html>
What im trying to do is within cel 5 (delete entry) is to add a delete button to each row that is entered into the table that will remove that row but don't know how to go about this. Ideally would like to do this without the use of JQuery if possible, since i've not touched upon it as of yet.
You can use the rowIndex property to delete the row.
function addRow() {
// get input values
var name = document.getElementById('name').value;
var currentAge = document.getElementById('currentAge').value;
var Birthday = document.getElementById('Birthday').value;
var carType = document.getElementById('carType').value;
var table = document.getElementsByTagName('table')[0];
const index = table.rows.length;
var newRow = table.insertRow(index);
newRow.setAttribute('data-index', index);
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
var cel4 = newRow.insertCell(3);
var cel5 = newRow.insertCell(4);
cel1.textContent = name;
cel2.textContent = currentAge;
cel3.textContent = Birthday;
cel4.textContent = carType;
cel5.innerHTML = '<button onclick="removeRow(this)" type="button" class="delete-button">Delete</button>';
}
function myFunction() {
var x = document.getElementById("table").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + "tr elements in the table.";
}
function removeRow(evt) {
const deleteIndex = evt.parentElement.parentElement.rowIndex;
document.getElementById("table").deleteRow(deleteIndex);
}
table,
th {
border: 1px solid black;
}
tbody td {
padding: 30px;
}
tbody tr:nth-child(odd) {
background-color: #F4BC01;
color: #ABC412;
}
<h2>Basic HTML table</h2> <button onclick="myFunction()">Press me for
elements amount</button>
<p id ="demo"></p>
Name: <input type="text" name="name" id="name" /><br/><br/>
Age: <input type="text" name="currentAge" id="currentAge" /><br/><br/>
Date of Birth <input type="date" name="Birthday" id="Birthday" /><br/>
<button onclick="addRow();">Display</button><br/><br/>
<p>Eye Colour:</p>
<select id="carType">
<option value="ferrari" id="ferrari">Ferrari</option>
<option value="lamborghini" id="lamborghini">Lamborghini</option>
<option value="porsche" id="porsche">Porsche</option>
<option value="bugatti" id="bugatti">Bugatti</option>
<option value="pagani" id="pagani">Pagani</option>
</select>
<table border="1" id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Birthday</th>
<th>CarType</th>
<th>Delete</th>
</tr>
</table>
</body>
</html>
What you should be doing is that you set the innerHTML of cel5 to a button, e.g.:
cel5.innerHTML = '<button type="button" class="delete-button">Delete</button>';
Then, you can simply add a click event listener on the table, and check if a click event has emitted from the button element. If it matches, you then delete the closest <tr> element:
document.getElementById('table').addEventListener('click', function(e) {
// Check if click event came from delete button
if (!e.target.classList.contains('delete-button'))
return;
e.target.closest('tr').remove();
});
See proof-of-concept example below:
function addRow() {
// get input values
var name = document.getElementById('name').value;
var currentAge = document.getElementById('currentAge').value;
var Birthday = document.getElementById('Birthday').value;
var carType = document.getElementById('carType').value;
var table = document.getElementsByTagName('table')[0];
var newRow = table.insertRow(table.rows.length / 2 + 1);
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
var cel4 = newRow.insertCell(3);
var cel5 = newRow.insertCell(4);
cel1.innerHTML = name;
cel2.innerHTML = currentAge;
cel3.innerHTML = Birthday;
cel4.innerHTML = carType;
cel5.innerHTML = '<button type="button" class="delete-button">Delete</button>';
}
function myFunction() {
var x = document.getElementById("table").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + "tr elements in the table.";
}
document.getElementById('table').addEventListener('click', function(e) {
// Check if click event came from delete button
if (!e.target.classList.contains('delete-button'))
return;
e.target.closest('tr').remove();
});
<h2>Basic HTML table</h2> <button onclick="myFunction()">Press me for
elements amount</button>
<p id="demo"></p>
Name: <input type="text" name="name" id="name" /><br/><br/> Age: <input type="text" name="currentAge" id="currentAge" /><br/><br/> Date of Birth <input type="date" name="Birthday" id="Birthday" /><br/>
<button onclick="addRow();">Display</button><br/><br/>
<p>Eye Colour:</p>
<select id="carType">
<option value="ferrari" id="ferrari">Ferrari</option>
<option value="lamborghini" id="lamborghini">Lamborghini</option>
<option value="porsche" id="porsche">Porsche</option>
<option value="bugatti" id="bugatti">Bugatti</option>
<option value="pagani" id="pagani">Pagani</option>
</select>
<table border="1" id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Birthday</th>
<th>CarType</th>
<th>Actions</th>
</tr>
</table>
In the head, add a function that understands rows and cells. Call some delete on a parent of a cell (Delete the <tr> in which the <td> is located at). then on the body add to each dynamic button an onClick event and set that function you created earlier ON.
You can use a script like this:
function deleteRow() {
var tableData = event.target.parentNode;
var tableRow = tableData.parentNode;
tableRow.parentNode.removeChild(tableRow);
}
In the button you create (dynamically or fixedly) you should add an onClick event. For example:
<tr>
<td>John Doe</td>
<td>$10,000</td>
<td><input type="submit" value="Delete" id="Delete" onclick="deleteRow()"></td>
</tr>

How to generate a unique id everytime I press a button in JavaScript

I want to make a site where a group of people have to add some data, later I will store them into a database.
I don't know the exact number of people and the exact number of rows so I made a function in JavaScript that generates a table when a button is pressed, and same with the rows.
I have some problems that I can't find the solution, that's why I ask here for help:
When I press the button "Add new Table" is like he enters on another page to load it. I tried to use tag and also but still the same.
When I press on "addRow" he put the id(number) 1 again, but I incremented the counter, again I don't know where is happend this.
When I add a new table and I try to add a row to it, he put the row to the first table, I was thinking that this is happend because all the tables have the same id, but why he don't add a row to all of them?
I want to add the row to that particular table where I press the button. My solution would be to add a particular id to every table.
I tried this:
var tableId = 1;
document.write('<div class="window_wrap"> <table class="window" id="idWindowTable' + tableId++ + '">' + table + '</table> </div>');
but I don't know how to increment the id in the addRow function:
var windowTab = document.getElementById("idWindowTable");
Here is my script:
<script>
var table = ''; //table from genTab
var rows = 1; //for genTab
var cols = 3; //for genTab
var rowCounter = 3; //starts from index 3 when add row on table
var nr = 1; // write the id at the number
var tableId = 1;
function genTab() {
table += '<tr> <th class="window_cells" colspan="3"><form class="window_form"><span>Cordonator: </span><input type="text" name="prof_name" placeholder="Prof. dr. Nume Prenume" required/><input type="email" name="prof_email" required/><input type="submit" value="Submit"/></form></th> </tr> <tr><td class="window_cells">Nr</td> <td class="window_cells" id="test">Tema</td> <td class="window_cells">Detalii</td> </tr>';
for(var r = 0; r < rows; r++)
{
table += '<tr>';
for(var c = 0; c < cols; c++)
{
if(c==0)
table += '<td class="window_cells">' + nr++ + '</td>';
else
table += '<td class="window_cells"> <textarea rows="4" cols="30"> </textarea> </td>';
}
table += '</tr> <tr> <th class="window_cells" colspan="3"> <form> <input type="button" value="Preview"/> <input type="submit" value="Submit row"/> <input type="button" value="Add new Table" onClick="genTab()"/> <input id="idRowButton" type="button" value="Add row" onClick="addRow()"/> </form> </th> </tr>';
}
document.write('<div class="window_wrap"> <table class="window" id="idWindowTable">' + table + '</table> </div>');
nr = 1;
table = '';
}
function addRow() {
var windowTab = document.getElementById("idWindowTable");
var roww = windowTab.insertRow(rowCounter++);
var cell1 = roww.insertCell(0);
var cell2 = roww.insertCell(1);
var cell3 = roww.insertCell(2);
cell1.innerHTML = nr++;
cell1.className = "window_cells";
cell2.innerHTML = "<textarea rows=\"4\" cols=\"30\"> </textarea>";
cell2.className = "window_cells";
cell3.innerHTML = "<textarea rows=\"4\" cols=\"30\"> </textarea>";
cell3.className = "window_cells";
}
genTab();
</script>
Here is a begin. Use innerHTML and remove the nr=1 in the genTab function
var table = ''; //table from genTab
var rows = 1; //for genTab
var cols = 3; //for genTab
var rowCounter = 3; //starts from index 3 when add row on table
var nr = 1; // write the id at the number
var tableId = 1;
function genTab() {
table += '<tr> <th class="window_cells" colspan="3"><form class="window_form"><span>Cordonator: </span><input type="text" name="prof_name" placeholder="Prof. dr. Nume Prenume" required/><input type="email" name="prof_email" placeholder="(email#info.uvt.ro)" required/><input type="submit" value="Submit"/></form></th> </tr> <tr><td class="window_cells">Nr</td> <td class="window_cells" id="test">Tema</td> <td class="window_cells">Detalii</td> </tr>';
for (var r = 0; r < rows; r++) {
table += '<tr>';
for (var c = 0; c < cols; c++) {
if (c == 0)
table += '<td class="window_cells">' + nr+++'</td>';
else
table += '<td class="window_cells"> <textarea rows="4" cols="30"> </textarea> </td>';
}
table += '</tr> <tr> <th class="window_cells" colspan="3"> <form> <input type="button" value="Preview"/> <input type="submit" value="Submit row"/> <input type="button" value="Add new Table" onClick="genTab()"/> <input id="idRowButton" type="button" value="Add row" onClick="addRow()"/> </form> </th> </tr>';
}
document.getElementById("content").innerHTML+='<div class="window_wrap"> <table class="window" id="idWindowTable">' + table + '</table> </div>';
table = '';
}
function addRow() {
var windowTab = document.getElementById("idWindowTable");
var roww = windowTab.insertRow(rowCounter++);
var cell1 = roww.insertCell(0);
var cell2 = roww.insertCell(1);
var cell3 = roww.insertCell(2);
cell1.innerHTML = nr++;
cell1.className = "window_cells";
cell2.innerHTML = "<textarea rows=\"4\" cols=\"30\"> </textarea>";
cell2.className = "window_cells";
cell3.innerHTML = "<textarea rows=\"4\" cols=\"30\"> </textarea>";
cell3.className = "window_cells";
}
window.onload = function() {
genTab();
}
<div id="content"></div>

I have a table in jsp which have 5 rows and 3 colums and i wanted to print it in servlet how can i do this?

<script>
function addRow() {
var medicinename = document.getElementById("medicinename");
var time = document.getElementById("time");
var duration = document.getElementById("duration");
var when = document.getElementById("when");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(1).innerHTML= medicinename.value;
row.insertCell(2).innerHTML= time.value;
row.insertCell(3).innerHTML= duration.value;
row.insertCell(4).innerHTML= when.value;
document.getElementById('medicinename').value='';
document.getElementById('time').value='';
document.getElementById('duration').value='';
document.getElementById('when').value='';
}
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<3; i++){
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j=0; j<4; j++){
var td = document.createElement('TD');
td.width='75';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
</script>
<table>
<tr>
<td>Medicine Name:</td>
<td><input type="text" id="medicinename"></td>
</tr>
<tr>
<td>Time:</td>
<td><input type="text" id="time">
</tr>
<tr>
<td>Duration:</td>
<td><input type="text" id="duration">
</tr>
<tr>
<td>When?</td>
<td><input type="text" id="when">
<input type="button" id="add" value="Add" onclick="Javascript:addRow()"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
<div id="mydata">
<table id="myTableData" border="1" cellpadding="2">
<tr>
<td> </td>
<td><b>Medicine Name</b></td>
<td><b>Medicine Time&nbsp</b></td>
<td><b>Medicine Duration</b></td>
<td><b>Medicine When?</b></td>
</tr>
</table>
here is JAVASCRIPT through which i add element in JSP table
here is my 4 field and table which display data inside JSP
hello = request.getParameter("");//what should i take here
System.out.println(hello);
You need to collect your table data in JavaScript by the use a form or Ajax to send this data to your servlet. You can't get the table data from request parameters in servlet unless you send it.
An example of form
<form action="login" method="post">
<input type="text" name="uname" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit" class="button" >Login</button>
</form>
This form pass uname and password to login Servlet.
You can pass each data in table like this way...!
In servlet side you can use this code for fetch data
String uname = request.getParameter("uname");
String password = request.getParameter("password");
just try out..!
Since, you were using jQuery and Servlet but you edited your question and removed the code. But here is some code example using jQuery.
Sample Table :
<table id='table_id'>
<th>Column1</th><th>Column2</th>
<tr>
<td>1</td><td>2</td>
</tr>
<tr>
<td>3</td><td>4</td>
</tr>
</table>
First you need to iterate through your table in javascript, create a JSON object with table data. Probably like this (see the table structure given here)
<script type="text/javascript" >
function collectData(){
var tableData = [];
$('#table_id tr').each(function(){
var $this = $(this);
var tds = $this.find('td');
var i = 0;
//if we have data in that row
if(tds.length){
var rowData = {
column1:tds[0].innerHTML,
column2:tds[1].innerHTML,
}
tableData.push(rowData);
}
});
console.log(tableData);
// Send it via AJAX
$.ajax({
url: '/yourServletName', // Change name to your servlet
type: 'POST',
dataType: 'json',
data: {objarray: JSON.stringify(tableData)},
success: function(result) {
alert('SUCCESS');
}
});
}
JSON will be like :
{
[{'column1':1,'column2':2}, {'column1':3,'column2':4}]
}
Now in your servlet code access this data using
String tableArray = request.getParameter("objarray").
But you need to convert the JSON to Java Pojo Object. Create a class similar to your table and parse the JSON using any library like jackson or gson
public class TableData{
private String column1;
private String column2;
public String getColumn1(){
return column1;
}
public void setColumn1(String column1){
this.column1 = column1;
}
public String getColumn2(){
return column2;
}
public void setColumn2(String column2){
this.column2 = column2;
}
}
GSON tutorial is given here
As explained in another answer, either use input elements in form or use JSON object as given in another answer here.
Form input method
HTML or JSP
<table>
<tr>
<td>Medicine Name:</td>
<td><input type="text" id="medicinename"></td>
</tr>
<tr>
<td>Time:</td>
<td><input type="text" id="time">
</tr>
<tr>
<td>Duration:</td>
<td><input type="text" id="duration">
</tr>
<tr>
<td>When?</td>
<td><input type="text" id="when">
<input type="button" id="add" value="Add" onclick="Javascript:addRow()"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
<div id="mydata">
<form action="yourServletName" method="post">
<table id="myTableData" border="1" cellpadding="2">
<tr>
<td> </td>
<td><b>Medicine Name</b></td>
<td><b>Medicine Time&nbsp</b></td>
<td><b>Medicine Duration</b></td>
<td><b>Medicine When?</b></td>
</tr>
</table>
<button type="submit" class="button" >Submit</button>
<!-- Update the rowCount on Submitting the button -->
<input type="hidden" id="rowCount" value="" />
</form>
</div>
JS File to add input in table, you can :
function addRow() {
var medicinename = document.getElementById("medicinename");
var time = document.getElementById("time");
var duration = document.getElementById("duration");
var when = document.getElementById("when");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(1).innerHTML= '<input type="text" name="'+'rowMedicine'+rowCount+'" value="'+medicinename.value+'" readonly />';
row.insertCell(2).innerHTML= '<input type="text" name="'+'rowTime'+rowCount+'" value="'+time.value+'" readonly />';
row.insertCell(3).innerHTML= '<input type="text" name="'+'rowDuration'+rowCount+'" value="'+duration.value+'" readonly />';
row.insertCell(4).innerHTML= '<input type="text" name="'+'rowWhen'+rowCount+'" value="'+when.value+'" readonly />';
document.getElementById('medicinename').value='';
document.getElementById('time').value='';
document.getElementById('duration').value='';
document.getElementById('when').value='';
}
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<3; i++){
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j=0; j<4; j++){
var td = document.createElement('TD');
td.width='75';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
In your servlet, use the request.getParameter to access values.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Now, you can get the parameter from input elements using name
String rowMedicine = request.getParameter("rowMedicine1");
//Similarly get the values of all parameters using names
//get the row count
//iterate through it and save it in your database
}

Retrieving multiple Rows from database using javascript and display in an html table

I am trying to display the database values in a html table using javascript but i am getting only the last value in the database table
function productValues() {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
var responseJson= JSON.parse(xmlHttp.responseText);
var length=responseJson.a1.length;
document.getElementById("nid").value="";
document.getElementById("pid").value="";
document.getElementById("cid").value="";
document.getElementById("name").value="";
document.getElementById("price").value="";
for(i=0;i<length;i++){
var a=responseJson.a1[i];
var b=responseJson.a2[i];
var c=responseJson.a3[i];
var d=responseJson.a4[i];
var e=responseJson.a5[i];
document.getElementById("nid").value=a;
document.getElementById("pid").value=b;
document.getElementById("cid").value=c;
document.getElementById("name").value=d;
document.getElementById("price").value=e;
}
}
}
//response
ProductSearch prod=new ProductSearch();
prod.setA1(a1);
prod.setA2(a2);
prod.setA3(a3);
prod.setA4(a4);
prod.setA5(a5);
String responseJson = new Gson().toJson(prod);
//html code
</head>
<form id="form1" method="post" action="ProductNameSearchF">
<table align="center">
<tr>
<td><font color="#006400"><b> Select Item:</b></font>
<input type="text" name="searchname" id="user" onclick="clearFields()"/>
<input type="button" id="submit" style=" color:#280000 ;font-size: medium;" value="Edit" onclick="getDetails();" />
<tr>
<br/></td></tr>
<div id="welcometext" align="center">
</div>
</table>
<TABLE cellpadding="8" id ="table" border="1" align="center" style="background-color: #EEEEEE;">
<TR bgcolor="#66CCFF"><font color="#fff">
<TD color="#0080FF" width="0.1%" ><B>Id</B></TD>
<TD color="#0080FF" width="0.5%"><B>ProductType_Id</B></TD>
<TD width="0.1%"><B>Cuisine_Id</B></TD></font>
<TD width="0.5%"><B>Name</B></TD></font>
<TD width="0.5%"><B>Price</B></TD></font>
</TR>
<TR>
<TD><input type="text" name="id" id="nid" style="background-color:transparent; color:blue; " readonly ></TD>
<TD><input type="text" name="productid" id="pid" style="background-color:transparent; color:red; " ></TD>
<TD><b><input type="text" name="cuisineid" id="cid" style="background-color:transparent; color:red; " ></b></TD>
<TD><b><input type="text" name="name" id="name" style="background-color:transparent; color:red; "></b></TD>
<TD><b><input type="text" name="price" id="price" style="background-color:transparent; color:red;" ></b></TD></input>
</TR>
</font>
<font size="+3" color="red"></b>
</font>
<TR>
</tr>
</TABLE>
<table align="center">
<tr>
<td colspan=""> <img src="clear.jpg" width="50" height="30" ></img> <button type="submit" name="someName" value="someValue"><img src="redsubmit.png" width="70" height="30" ></button> </td>
</tr>
</table>
</table>
</form>
Here is my html code , i am adding only the essntial code of the html page
#user3825041: In Html elements id a are unique in nature. I mean if we you repeatedly set same ids with different values, at the end you will have single value(i.e is the last one) updated. Due to which you are getting only last value.
Please try to change ids with each row update.
Or else you can use html table plugins like bootstrap table which are easy and responsive to use. You just need to provide data(JSON/XML format) to these plugins.
http://getbootstrap.com/css/#tables
You can generate table dynamically from javascript, to achieve it your (servlet) response should be like:
ArrayList<ProductSearch> al = new ArrayList<ProductSearch>();
... databse code ...
while(rs.next()) {
ProductSearch prod=new ProductSearch();
prod.setA1(a1);
prod.setA2(a2);
prod.setA3(a3);
prod.setA4(a4);
prod.setA5(a5);
al.add(prod);
}
...
String responseJson = new Gson().toJson(al);
response.getWriter().println(responseJson);
And your html should be like:
<input type="button" value="Show Results" onclick="showTable()" />
<div id="dvTable"></div>
<script type="text/javascript">
function showTable() {
if (xmlHttp.readyState == 4) {
var responseJson = JSON.parse(xmlHttp.responseText);
var table = document.createElement("TABLE");
table.border = "1";
var row = table.insertRow(-1);
var headerCell = document.createElement("TH");
headerCell.innerHTML = "nid";
row.appendChild(headerCell);
var headerCell = document.createElement("TH");
headerCell.innerHTML = "pid";
row.appendChild(headerCell);
var headerCell = document.createElement("TH");
headerCell.innerHTML = "cid";
row.appendChild(headerCell);
var headerCell = document.createElement("TH");
headerCell.innerHTML = "name";
row.appendChild(headerCell);
var headerCell = document.createElement("TH");
headerCell.innerHTML = "price";
row.appendChild(headerCell);
for (var i = 0; i < responseJson.length; i++) {
row = table.insertRow(-1); //creates new row
row.id = "row1"; // if you want to set id of row
var cell = row.insertCell(-1); // creates new column
cell.innerHTML = responseJson[i].a1; // put data in column
cell.id = "column1"; // if you want to set id of column
var cell = row.insertCell(-1);
cell.innerHTML = responseJson[i].a2;
var cell = row.insertCell(-1);
cell.innerHTML = responseJson[i].a3;
var cell = row.insertCell(-1);
cell.innerHTML = responseJson[i].a4;
var cell = row.insertCell(-1);
cell.innerHTML = responseJson[i].a5;
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
}
</script>

Categories

Resources