Save dynamic data created using createElement(Javascript) to database - javascript

I am new to this forum as well as webpage designing. I am trying to design a profile management tool using JSP in which there are dynamically added(through javascript createElement) input fields to which names are assigned. I am able to save only one record to database and others are ignored.
My question is how to save all the data that is dynamically added?
Please help me on this.
Javascript code:Using the below function, I am able to get Javascript array
function addedu()
{
$(document).ready(function(){
$(".ed").each(function(input){
var value = $(this).val();
var id = $(this).attr('id');
t= id+' : '+ value;
arr.push(t);
});
});
var newinput1 = document.createElement("input");
newinput1.name="i1"
newinput1.className="ed"
newinput1.id="Education"
newinput1.innerHTML = "";
document.getElementById('edu').appendChild(newinput1);
}
JSP code:
String edu1=request.getParameter("i1");
Statement st1=con.createStatement();
String sql1="insert into education values('"+pno+"','"+edu1+"');
st1.executeUpdate(sql1);

On the client side you can use jQuery to dynamically add rows and read necessary values. To access the rows of the table you can use jQuery selectors. Then save the data in the JavaScript array, convert it to JSON and send it to the server side.
Here is an example (with using PHP, but in this case it doesn't matter):
Store HTML Table Values in a Javascript Array and Send to a PHP Script Using jQuery and Ajax
On the server side you'll need to make a lot of inserts via plain JDBC, use BATCH insert instead of hitting database once for each insert statement.
Here is an example:
Java: Insert multiple rows into MySQL with PreparedStatement
If you'll decide to use Spring, here is an example:
How to Insert multiple rows from web form into database using java spring framework

Related

Issue with ng-html-compile displaying UI-Grid twice while rendering saved HTML from SQL Server Database

1)I am saving entire DIV - TestDIV from a HTML page in AngularJS to SQLServer database.
2)TestDIV has many DIVs nested inside it, including UI-Grids.
3)I save the HTML as a VARCHAR(MAX) column in SQL Server. I am able to save and retrieve the HTML correctly.
4)On page - Test.HTML - I have a another DIV - with ID = TestDIVDisplayed
5)I am assigning saved HTML to TestDIVDisplayed using ng-html-compile. Basically setting ng-html-compile to HTMLBindValue
6)This seems to work, with an issue esp. with UI-Grid. The UI-Grid is displayed twice, instead of once. Something similar to the following -
7)The assignment is done the following way in JavaScript code -
var toChg = 'TestDIVDisplayed';
var btn = document.querySelector('#' + toChg);
btn.setAttribute("ng-html-compile", "HTMLBindValue");
var el = $(btn);
$compile(el)($scope);
$scope.mySidenav = entity.DivSavedInSQLServerDatabase; //Getting the entity.DivSavedInSQLServerDatabase from a WebAPI service call.

(XPages)Can use Javascript to connect ODBC data to show on XPages?

I have some data stored in ODBC, and those data look like this:
Does anyone use calculated fields or other functions to display ODBC data in XPages?
I need to display the data stored in ODBC in XPages, and then write other data to save back to ODBC.
Originally used ASP to write this function, the writing method is as follows:
Set conn = Server.CreateObject("ADODB.Connection")
conn.open b8_dsn
SQL = "SELECT PONUM as PONUM,COMP_NAME as Company,CASENAME AS Case_name,PRICE as Price"
SQL = SQL & " FROM CB4_AUCTION"
Set rs = conn.Execute(SQL)
Your best course of action is to encapsulate the ODBC (actually more JDBC) data into a managed bean. Design one property of the bean to be like
public List<SomeData> getRows();
and you can use beanName.rows directly in a repeat control as data source.
Design the SomeData as Java bean (which is fancy for: having getSomeValue(), setSomeValue(...) pairs of methods, so you can directly bind them to a form using beanInstanceName.someValue (where beanInstanceName is the variable name of your repeat control)
You can read about bean data binding here:
https://wissel.net/blog/2011/01/binding-controls-to-managed-beans.html
And how to save yourself some headache by creating and testing your bean outside of XPages first here:
https://wissel.net/blog/2013/06/managed-beans-xpages-and-testability.html
You want to use the extension library, which comes with ODBC/JDBC stuff and check related questions:
How do I access SQL from XPages
XPages JDBC connected to MS ACCESS DB, issue showing data in ViewPanel
Let us know what worked for you!

Jquery exporting table to csv hidden table cells

I need to be able to export a HTML table to CSV. I found a snippet somewhere; it works but not entirely how I want it to.
In my table (in the fiddle) I have hidden fields, I just use quick n dirty inline styling and inline onclicks to swap between what you see.
What I want with the export is that it selects the table as currently displayed. so only the td's where style="display:table-cell". I know how to do this in normal JS.
document.querySelectorAll('td[style="display:table-cell"])');
but how can I do this using the code I have right now in the exportTableToCSV function?
(sorry but the text in the fiddle is in dutch as its a direct copy of the live version).
The fiddle:
http://jsfiddle.net/5hfcjkdh/
In your grabRow method you can filter out the hidden table cells using jQuery's :visible selector. Below is an example
function grabRow(i, row) {
var $row = $(row);
//for some reason $cols = $row.find('td') || $row.find('th') won't work...
//Added :visisble to ignore hidden ones
var $cols = $row.find('td:visible');
if (!$cols.length) $cols = $row.find('th:visible');
return $cols.map(grabCol)
.get().join(tmpColDelim);
}
Here's how i solved it. Decided to step away from a pure javascript solution to take processing stress off the client and instead handle it server side.
Because i already get the data from the database using a stored procedure i use this to just get the dataset again and convert it into an ViewExportModel so i have a TotalViewExport and a few trimmed variations (reuse most of them) based on a Selected variable i fill a different model.
Added to the excisting show function to update a Selected variable to keep track of the currently selected view.
When the user clicks Export table to excel it calls to the controller of the current page, IE. AlarmReport (so AlarmReportController) and i created the action ExportReports(int? SelectedView);
In addition i added CsvExport as a manager. This takes data results (so c# models/ iqueryables/ lists/ etc). and puts them into a Csv set. using the return type BinaryContent one can export a .csv file with this data.
The action ExportReports calls the stored procedure with the selectedview parameter. The result gets pumped into the correct model. this model is pumped into the CsvExport model as rows.
The filename is made based on the selected view + What object is selected + current date(yyyy-MM-dd). so for example "Total_Dolfinarium_2016-05-13". lets
lastly the action returns the .csv file as download using the BinaryContent Returntype and ExportToBytes from the CsvExport
The export part of this action is programmed like so(shortened to leave some checks out like multiple objects selected etc)(data and objectnames are gathred beforehand):
public ActionResult ExportCsv(CsvExport Data, string ObjectName, string Type){
var FileName = Type + "_" + ObjectName + "_" + DateTime.Now.ToString("yyyy/MM/dd");
return BinaryContent("text/csv", FileName + ".csv", Data.ExportToBytes());
}

Accessing objects/rows created in ASP.NET from Javascript

I create a table dynamically and add rows, labels etc to it.
I want to be able to access those rows to make either visible or hidden AND access labels to change content on the fly. So far the table and all info is created with no problem. I spent days trying to access the data from JS, but I keep getting NULL etc on objects using ALERT to test it. Here's a snippet example of my code...
ASP.NET (C#) code
mTable = new HtmlTable();
mTable.ID = "mTable";
aCell = new HtmlTableCell();
aLabel = new Label();
aLabel.ID = "aLabel";
aLabel.Text = "TEST";
aCell.Controls.Add(aLabel);
aRow = new HtmlTableRow();
aRow.ID = "r" + x;
aRow.Cells.Add(aCell);
mTable.Controls.Add(aRow);
Ive put the following code in a SCRIPT FILE etc and ive tried many styles.
alert(document.getElementById('<%=aLabel.ClientID%>'));
If you are using plain vanilla javascript, please look at the code sample here: How do I iterate through table rows and cells in javascript?
The code sample in the above link gets the table by id, which in your case is 'mTable' (from your c# code)
var table = document.getElementById('mTable');
// will return you a reference to the table object on the page
You also have to place the code to call your javascript function that accesses data on the 'mTable' on the document load event

Shiny - store javascript variable to mysql database

I am working with shiny server.
My application has a search box input. Based on that input, the output is a dataTable which has clickable links.
My application's ui.r contains a JavaScript function that sets the value of a variable whenever a link is clicked. Let the variable be clickedLink. Now I want to store this value of link to mysql or any other database. How to go about this?
I have tried ajax , php with no use. What I did is described in this question: saving json data to json file using ajax PHP but I guess php files do not work with shiny. Please help.
EDIT 1
code added to ui.R
tags$script(HTML("
function clickFunction(clickedLink){
//alert(clickedLink);
var cl = clickedLink;
Shiny.onInputChange('clickedLink',cl);
}
"))
code added to server.R
observe({
print(input$clickedLink)
})
EDIT 2
Just for information , the links are of the form
<a onclick="clickFunction(this.href); " target="_blank" href="http://SOMETING.com">SOMETHING</a>
I'm assuming you know how to save the variable once you get it in R. If not, use the RMySQL package and read their tutorial - https://github.com/rstats-db/RMySQL
So your main problem is getting the javascript variable into R. For that you can use Shiny.onInputChange. There's a short easy tutorial here https://ryouready.wordpress.com/2013/11/20/sending-data-from-client-to-server-and-back-using-shiny/
Basically, in javascript you would have
Shiny.onInputChange("jsvar", clickedLink) and then you can treat jsvar as a regular reactive input, so in R you can do `observe({ saveToDb(input$jsvar) }) (you'd have to define saveToDb)

Categories

Resources