O'Reilly logo

Ajax on Rails by Scott Raymond

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

JavaScript Libraries and Prototype

If you’re new to Ajax, you’re hopefully starting to see that doing vanilla Ajax, without the support of any extra libraries or helpers, isn’t the trick it’s often portrayed to be. Nonetheless, the idea of writing more than a dozen lines of code to do the simplest possible task is off-putting.

Dozens of JavaScript libraries have sprung up to make Ajax easier, and one of the most popular is Prototype, which is included with Rails. We’ll cover Prototype thoroughly in Chapter 10, but for now, let’s dive in with some examples. First off, let’s redo the last example, this time using Prototype. Here is a new chunk to add:

<script src="/javascripts/prototype.js" type="text/javascript">
</script>
<p><a href="#" onclick="prototypeAlert();">Call with Prototype</a></p>
<script type="text/javascript">
 function prototypeAlert() {
  new Ajax.Request('/chapter2/myresponse', { onSuccess: function(request) {
   alert(request.responseText);
  }})
 }
</script>

Note the first line, where we include the prototype.js source file so that it’s usable from our page. When you first generated a new Rails app skeleton, a copy of Prototype was put in the directory public/javascripts. Inside the prototypeAlert() function, the first line creates a new instance of Ajax.Request, one of Prototype’s classes. The first argument takes the URL to be requested, and the second argument is a JavaScript object literal—a collection of key/value pairs, which behaves similar to a hash or associative ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required