Eight Weeks of Prototype: Week 8, A Complete Prototype Example
Saving a New Contact Using Ajax
Now we will define the AddressBook_Creator class, the purpose of which is to send the details of a new contact to the server using Ajax so that it can be saved to the database.
This class works by observing when the form created in Listing 8 is submitted and retrieving the values and submitting them using Ajax. Additionally, we must prevent the browser from submitting the form as normal. This is achieved using the Event.stop() method.
Listing 10 shows the code for the Creator.js, which should be saved to the /js/AddressBook directory.
var AddressBook_Creator = Class.create({ initialize : function(container) { this.container = $(container); this.form = this.container.down('form'); this.form.observe('submit', this._onFormSubmit.bindAsEventListener(this)) }, _onFormSubmit : function(e) { // stop the browser from submitting the form normally Event.stop(e); // create request options var options = { method : this.form.readAttribute('method'), parameters : this.form.serialize(true), onSuccess : this._onSaveSuccess.bind(this) } // clear the form values so it can be re-used this.form.reset(); // initiate the ajax request new Ajax.Request(this.form.readAttribute('action'), options); }, _onSaveSuccess : function(transport) { var json = transport.responseJSON; var errors = $A(json.errors); if (errors.size() > 0) alert('Error adding contact'); else if (json.contact) { // this condition means the contact was added, so trigger the custom event document.fire('contacts:added', { contact : transport.responseJSON.contact }); } } });
The concepts covered in this code have all been covered in previous articles in this series, however perhaps the most interesting part of this code is the case when a new contact is added. In this situation, we trigger a custom event called contacts:added (remember that in Prototype you must namespace your custom events with a colon). When firing a custom event you can also include memo data as the second argument to fire(), as done in this code with the new contact.
In the contact manager class (covered in this next section) we will observe this event so we can add any newly created contacts to the list without the page needing to be reloaded.
The other thing this code does is to read the form method and action straight from the HTML, allowing it to use the same handler script for the form as if Ajax wasn't used. This means that if you want to change the script that handles the form you don't have to change the JavaScript code.




