I fed up looking for a clear and easy to digest Rails Ajax example. I wanted to know how to make a
View and a
Controller exchange data via Ajax in json format, so I made this post to help me and hopefully you to avoid the
pain next time you need to implement such a thing! :D
In my scenario, a user clicks a
li element in my web page (
View). The text inside the
li is a file name, stored somewhere in my server.
Via Ajax send that text (file name) to the
Controller, return the contents of that file and display them in another part of
the same web page (
This is a simple diagram of the whole procedure
Web page (View) -> Click on li element -> Pass the file name to Controller -> Let Controller/Model do their magic and return the file contents back to View -> Update View
In order to keep it simply, only the necessary parts of the code are shown.
For the following snippets of Rails code assume that the
Model name is
Add the following
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
fileContent functionality in the controller
1 2 3 4 5 6 7 8 9
Add in your
routes.rb the Controller method responsible for the Ajax response
1 2 3 4 5 6
In a next post I will show you how to add mixed client/server side validation, for both file name and file extension.