Web Application 101

I often see questions on Stack Overflow that show an inherent misunderstanding of how web applications, and more specifically, ruby on rails, work. It usually involves some form of, “How do I run ruby code on a button click” or “How can I get these javascript variables to the parameters of this ruby function?”

The problem here is one of not understanding where certain code is executed in the cycle of a web app, so let’s review. In a nutshell:

Request Cycle Where it happens Primary language
Form Submission or Ajax request Browser html/css/javascript
GET/POST Network HTTP
Controller Server ruby
View erb/html/css (javascript set up but not executed)
HTML Response or JSON/XML Network HTTP
Render page or response Browser html/javascript

Anything that needs to be run in ruby has to be done so on the server, and anything done in javascript is done on the web browser. Thus, if you need to have some data in the browser, whether in a form or in javascript, interact with ruby code, you have to begin the whole cycle from the start. Bundle the data up into a form or an ajax request and send the request to the server. Have a rails controller/view respond to it. This can be a whole page, or it can be a JSON or XML response, whatever. Then the browser handles the response by rendering a new page or dynamically handling the response.

When you need data to cross from one environment to the other, you have to do it through a HTTP request. That is the core of web application technology!

Of course, the tricky part comes when the view is writing javascript that is going to be run in the browser. The key to remember is execution time, and when the data is available. You can put variables into javascript code to be run if you know it ahead of time:

[sourcecode language=”html”]
<script type="text/javascript">
alert("here is a ruby variable: <%= @foo %>");
</script>
[/sourcecode]

However, if the data is going to be decided by the actual execution of the javascript, it is too late to access it from ruby in this request cycle; time to generate a new request cycle!

Advanced solutions include sending along partials hidden in the page or javascript and then rendering them with javascript, such as with handlebars. That is a big enough subject for a future post.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *