12.7. User-Registration Component
The user-registration component provides a way for people to register themselves as users of the ticket manager application. It's a simple component, providing a form and the code needed to process that form using AJAX. An example of the form is shown in Figure 12-10, with the HTML that builds the UI shown in Listing 12-11.
Figure 12-10. User registration form
Listing 12-11. Register.php
Listing 12-12. Register.js
The register component doesn't need a setup function, so it starts by setting up its AJAX instance (line 6). It defines a single callback, addUser (lines 24), which calls the registerComplete function. Next we define the register function (lines 829), which is called when the registration form is submitted. The function grabs the values of the fields it will be submitting (lines 911) and then does some basic validation. If the validation fails, we use the setMessage function (lines 1415) to display a warning to the user and stop the form submission by returning false. Remember that validation is also enforced on the server, so we're not using this code to protect our back end, just to provide a good user experience. If the validation succeeds, we make an AJAX call to addUser, passing in the username, password, and email address (line 20). This call is followed by code that prepopulates the login form with the new username and password (lines 2223). The next step is to display the loading status, which is done by disabling the submission button of the registration form (lines 2527).
When the server has returned a response, the registerComplete function (lines 3137) is run by the callback function. This function selects the front page of the application (line 34), highlights the login form (line 33) to show the user that he or she should log in, and then re-enables the registration form (lines 3536) in case we want to register another user.