8

I want to send data from javascript to R using shiny js function, but is not working. What I have done is a simple example, in which setinputValue send "noone" to "too" input$too

Here is the code:

library(shiny)


ui <- fluidPage(

  HTML("<script>
       $( document ).ready(function() {
       Shiny.setInputValue('too', 'noone');

       });</script>"),


      textOutput("table")


  )


server <- function(input, output) {
 output$table <- renderPrint(input$too)


}

 shinyApp(ui,server)

The js error I get is: Shiny.setInputValue is not a function

2 Answers 2

14

It does not work with $( document ).ready(function(), but with $( document ).on("shiny:sessioninitialized", function(event) {:

library(shiny)  
ui <- fluidPage(      
  HTML('<script>
       $( document ).on("shiny:sessioninitialized", function(event) {
           Shiny.onInputChange("too", "noone");           
       });</script>'),         
  textOutput("table")      
)

server <- function(input, output) {
  output$table <- renderPrint(input$too) 
}

shinyApp(ui,server)

Reason for this is given in the tutorial: You cannot call the function too soon, you need a little time until Shiny is ready to update the input value:

in message.js, we wrapped our code in $(document).ready(function() { ... }. This jQuery function will tell the browser to only run the code inside, once the page, i.e. the Document Object Model (DOM), is ready for JavaScript code to execute. Note that when we activate this code too soon, i.e. before the image is loaded, we cannot yet attach an event handler to it. In other words, here we want to be sure that the image exists before attaching an event handler to it. ```

Sign up to request clarification or add additional context in comments.

Comments

0

I just wanted to point out that the function being called in the answer by shosaco differs from original post which isn't that clear from the reasons why it didn't work.

Shiny.setInputValue('too', 'noone');

to

Shiny.onInputChange("too", "noone");           

1 Comment

As pointet out in this tutorial they are equivalent after v1.1, being setInputValue() the newer version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.