Example 2 – sending messages between client and server

In this example, we are going to use the DOM and messages to pass information between the client and server. The user will be able to select a number using a slider. The server reads this input and then picks a random number between 1 and the user-supplied number. This number is written back to the screen as well as being sent in a message to JavaScript.

JavaScript receives this number and produces a drop-down selector that allows the user to select a value between 1 and the random number that the server picked. Every time the user selects a different value from this dropdown, JavaScript will decide randomly whether it thinks that Shiny rules! or whether, in fact, JavaScript rules!. This is sent as a message to the server, which picks it up and writes it to the screen. Clearly, this is not of much use as a real application, but it should demonstrate to you the principles of sending and receiving messages and reading and writing to the DOM.

It is definitely worth having a look at the application live. As with all the applications, it can be run straight from my website (chrisbeeley.net/website) where the source code can also be downloaded. Here is the application in action:

As you can see in the previous screenshot, the user has picked 7, the server has picked 6 out of the range of numbers from 1 to 7, JavaScript has built a drop-down menu using that number of options, and has also decided in this case that JavaScript rules. Do note that this application could quite easily be written in pure Shiny, and, like many examples in this book, is provided for illustration only. It is worth keeping it simple, so you can easily see how everything fits together without worrying about understanding everything JavaScript is doing.

In this case, the ui.R and server.R files are both pretty simple and should be fairly self-explanatory. Most of the code is in the JavaScript file. Let's quickly look at the ui.R and server.R files first.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset