Shiny - store javascript variable to mysql database - javascript

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)

Related

sending JSON Object from python to javascript to populate dropdown list

I want to add a dropdown list to my table (for each row in same column).I managed to do this but only if the arrays are written in the javascript.
What I want to do now, is to populate my dropdown list with the values from an Excel file. Since that is not so easy I created a python file where I convert this excel file as a JSON file and take only the sheet from where the values should be imported. But What I don't know is how to call my JSON object from python in the javascript
convert_excel_file.py :
import pandas as pd
path_to_excel = "//10.0.254.14/data/file_to_read_from.xlsm"
export_m42OUs = pd.read_excel(path_to_excel,sheet_name='m42OUs')
json_m42OUs = export_m42OUs.to_json(orient='records')
print(json_m42OUs)
which gives me JSON file that looks something like this :
[{"OU_ID":"OU00001","OU_IDName":"Global"},
{"OU_ID":"OU00086","OU_IDName":"DEMO_01"},
{"OU_ID":"OU00087","OU_IDName":"DEMO_02"},
...]
I have to note that I can't just write the values in JS because the Excel file can be updated and new values can be added which is not the best solution for me.
I tried few codes I found on stack but none of them worked :/
EDIT : I corrected the path now it doesn't show 404Error anymore but I still don't know how to get the data . I just tried this code :
let dropdown = $('#OUsList');
dropdown.empty();
dropdown.append('<option selected="true" disabeld>Choose</option>');
dropdown.prop('selectedIndex',0);
const url='http://107.0.0.1:5000/my_app/convert_excel_file.py';
//Populate dropdown with the list
$.getJSON(url, function(data){
$.each(data, function(key,entry){
dropdown.append($('<option></option>').attr('value', entry.OU_ID).text(entry.OU_IDName))
});
});
EDIT 2:
after 15 sec after runing the code it returned me this error:
jquery-1.12.4.js:10254 GET http://107.0.0.1:5000/my_app/convert_excel_file.py net::ERR_CONNECTION_TIMED_OUT
You need create to a simple web app to serve your JSON, Your javascript looks OK but your server side python is not ran the way you intend to.
I'd recommend you use some lightweight framework like CherryPy to return a JSON HTPP response.

Python Flask data feed from Pandas Dataframe, dynamically define with unique endpoint

Hi I am building a web app with Flask Python. I got a problem here:
#app.route('/analytics/signals/<ticker_url>')
def analytics_signals_com_page(ticker_url):
all_ticker = full_list
ticker_name = com_name
ticker = ticker_url.upper()
pricerec = sp500[ticker_url.upper()].tolist()
timerec = sp500[ticker_url.upper()].index.tolist()
return render_template('company.html', all_ticker=all_ticker, ticker_name=ticker_name, ticker=ticker, pricerec=pricerec, timerec=timerec)
Here I am defining company pages based on the a page will contain different content. The problem is that everything is fine upto ticker = ticker_url.upper(). It works perfectly fine. But for pricerec and timerec, they make problems.
sp500 is a pandas DataFrame columns being companies like "AAPL", "GOOG","MSFT", and so forth 505 companies and the index are timestamps, and values are the prices at each time.
So what I am doing for the pricerec, I am taking the ticker_url and use it to take the specific company's price and make it as a list. And timerec is to take the index (timestamps) and make it as a list. And I am passing these two variables into the company.html page.
But it makes internal server error. I do not know why it happens.
My expectation was that when a user click a button that href to "~/analytics/signals/aapl" then the company.html page will contain the pricerec and timerec for me to draw a graph. But it didn't work like that. It makes internal server error. I defined those two variables in the javascript also like I did for the other variables(all_ticker, ticker_name, and ticker)
Can anyone help me with this issue?
Thanks!

Save dynamic data created using createElement(Javascript) to database

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

Dumbed down Powershell web client function to let me post form data easily

Ive been using an Internet Explorer automation script found here:
http://www.pvle.be/2009/06/web-ui-automationtest-using-powershell/
That lets me easily post form data using commands (functions) like this:
NavigateTo "http://www.websiteURI/"
SetElementValueByName "q" "powershell variable scope"
SetElementValueByName "num" "30"
SetElementValueByName "lr" "lang_en"
ClickElementById "sb_form_go"
The above would let me post values to elements and click to submit the form.
I would like to do the equivalent with Powershell's web client using helper functions. I haven't found such a script. The closest I could find was The Scripting Guys, Send-WebRequest:
http://gallery.technet.microsoft.com/scriptcenter/7e7b6bf2-d067-48c3-96b3-b38f26a1d143
which I'm not even sure it does what I expect (since there's no working examples showing how to do what I want).
Anyway, I'd really appreciate some help to get me started to do the equivalent of what I showed up there with working examples (as simple as possible). A bonus would be to also be able to get a list of element names for a URI in order to know what form elements I want to submit.
PS: I also need to be able to specify user-agent and credentials; so, examples with these included would be ideal.
Have you taken a look at the Invoke-WebRequest commmand? (requires powershell 3.0 or above) I believe the following would work for submitting the data
#POSTing data
Invoke-WebRequest http://www.websiteURI/ `
-UserAgent 'My User Agent' `
-Credential $cred `
-Method Post `
-Body #{
q = 'powershell variable scope'
num = 30
lr = 'lang_en'
}
For your bonus, the result of Invoke-WebRequest contains a collection of the InputFields on the page, which you can use to get a list of form elements to set.
#List input elements
Invoke-WebRequest http://www.websiteURI/ | select -ExpandProperty InputFields

Restore multiple selections from db using Rangy

What i want to do :
->Show a plain HTML page to a user
->User has the ability to highlight text on that page
->When user logs in next time , i should be able to retrieve and show his previous (multiple) highlight on the page.
What i have done :
I used the Library/API : Rangy.With this iam able to select the text and highlight it with the users preferred color.
The Problem :
I tried the serialize and de-serialize function , but when i try to deserialize (after page has been reloaded) it gives me an error saying
checksums of serialized range root node (ec0c8cf0) and target root
node (d4997863) do not match
Everytime i reload the page , there is a new root node , how can i fix the deserialize in this case ?
Created a JS-Fiddle : demo / js-fiddle
What is this - If you check my demo , i select the first word of the description ie "Please " , i get the text highlighted , and i also get the serial as :
0/3/1/3/0/1/1/2:9,0/3/1/3/0/1/1/2:9{b3002d92}
so what i did is , i hard coded this serial and put it into the deserializeSelection funciton in the page onLoad function like this :-
rangy.deserializeSelection('0/3/1/3/0/1/1/2:9,0/3/1/3/0/1/1/2:9{b3002d92}');
so technically , it should highlight the "Please" in the description , whenever the page loads , irrespectively.But it does not , instead give me the above error in block.
Can you help me solve this.please.Thank you
Extra:
1.I really do not understand the serialize and de-serialize methods of rangy.
2.My very abstract road map from here is to , do an AJAX call , on page load and fetch all (serialized) selection of the user for this page from my db and iterate over them and do a de-serialize.
Any help , would be really appreciated.
Thank you.
What I think is you should try this:
var selObj = rangy.getSelection();
var se = rangy.serializeSelection(selObj, true); //true to avoid DOM checksum

Categories

Resources