Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a button in Shiny to call both JavaScript and R code in parallel?

I have an HTML button in Shiny that when clicked, calls the JavaScript function geocodeAddressStreet(...) in a .js file in the /www directory:

tags$body(tags$input(type = "button", 
                     value = "Next", 
                     id = "button1", 
                     onClick = "geocodeAddressStreet(houseNumber,streetName,addressCity,addressState)"))),

However I cannot figure out how to get this button to call a second file when clicked, let's say foo.R. Both procedures run independently, but it seems like there's no way to add an inputId to an HTML element in Shiny. We currently have two different buttons, one of which calls R code and the other of which calls JavaScript code, but this is clearly an impractical solution.

like image 202
Brandon Sherman Avatar asked Jul 10 '15 17:07

Brandon Sherman


1 Answers

So you want to have a button and when you click it, both a javascript function and some R code get called? I was able to do this with the onclick function from the shinyjs package (disclaimer: I wrote the package)

library(shinyjs)

jsCode <- "
shinyjs.geocodeAddr = function(params) {
  alert('JavaScript called!');
  // geocodeAddressStreet(...)
}
"

runApp(shinyApp(
  ui = fluidPage(
    useShinyjs(),
    extendShinyjs(text = jsCode),
    actionButton("btn", "Click me")
  ),
  server = function(input, output, session) {
    onclick("btn", {
      js$geocodeAddr()
      cat("R called as well")
    })
  }
))

Basically, the onclick function is an R function that will run when the button is clicked. Within it you can obviously call R code easily, but you can also call JS code using the shinyjs package -- that's how I made a call to js$geocodeAddr. Look at the extendShinyjs function. Alternatively, instead of using extendShinyjs(), you can also use the usual approach of session$sendCustomMessage(...)

like image 85
DeanAttali Avatar answered Nov 07 '22 14:11

DeanAttali