Control Flow and User Input
While the birthday card is fun and easy to set up, the interaction is one-sided—from server to caller. Let’s now look at how to obtain information from a user and take action based on that input.
Figure 2 illustrates the simple architecture of the voice application that uses both forms and menu to drive the interaction. A menu is convenient for obtaining one of a set of options from a user. The form element is more general and can be used as a vocal equivalent of an HTML form to gather multiple data items from a user. In this simple example we’re simply using the form to talk to our user.
Figure 2 Using forms and menus in a VoiceXML application
In VoiceXML, forms and menus can reside in different files on a server, or all can be included in the same file. In this example, all the forms and the menu reside in the same file. To branch to a menu or form within a single XML document, we need to add an id attribute to our dialogs, as in the following:
<form id="world">
When the form or menu dialog has an id, it can be used as the target of a next branch, as in the following:
<choice dtmf="1" next="#world"/>
Listing 3 illustrates a simple voice application that prompts for a topic of interest and then delivers content based on the choice.
Listing 3 Branching based on user input
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE vxml SYSTEM "http://www.w3.org/TR/voicexml20/vxml.dtd"> 3 <vxml version = "2.0"> 4 <menu id="mainmenu"> 5 <prompt>For the world press 1, for sports press 2, 6 for people press 3. 7 </prompt> 8 <choice dtmf="1" next="#world"/> 9 <choice dtmf="2" next="#sports"/> 10 <choice dtmf="3" next="#people"/> 11 </menu> 12 <form id="world"> 13 <block> 14 The population of China is 200 billion. 15 </block> 16 </form> 17 <form id="sports"> 18 <block> 19 The New York Yankees won the 1955 world series. 20 </block> 21 </form> 22 <form id="people"> 23 <block> 24 Ulysses S Grant’s picture is on the U S 50 dollar bill. 25 <goto next="#mainmenu"/> 26 </block> 27 </form> 28 </vxml>
In Listing 3, the menu element contains four child elements: a prompt (lines 5–7) that announces the options, and three choice elements (lines 8–10) that specify the keypad inputs that will trigger a conditional jump to one of the three forms.
To pass control back to the main menu, each form includes a goto element with a next attribute that specifies the id of the dialog to jump to. When using goto, it’s important to place the goto element inside the block element. Blocks are used to hold executable content; if you place a goto outside the block, there will be no transfer of control, and your application will terminate.