• No results found

Posting Data to an Application Server

In document (This page intentionally left blank) (Page 136-145)

In jQuery Mobile, form submissions are automatically handled using Ajax whenever possible, resulting in a smooth transition between the form and the result page. If left unspecified, a form's method will default to get and its action will default to the current page's relative path

($.mobile.path.get())

Note that forms accept attributes for transitions just like anchors, so you can attach a data-transition="pop" and data-

direction="reverse".

If you do not want a page transition to occur or simply want more control over the submission process, you'll need to invoke the $.ajax() method as illustrated by the following example:

submitForm: function() {

var form = $("form#contactform"); var validator = form.validate(); validator.form(); if (validator.numberOfInvalids() == 0) { $.ajax({ type: "POST", url: "http://www.xdktraining.com/savecontact.cfm", data: form.serialize(), success: function(data) { alert("Record Saved"); },

error: function(XMLHttpRequest, textStatus, err){ var msg = ''.concat(

'status:', XMLHttpRequest.status, '\n', 'status text: ', XMLHttpRequest.statusText ); alert(msg); } }); } }

Note the following from the preceding example:

 Call the form.serialize() method to retrieve all form field values and serialize them into a single encoded string for posting to the app server.  You should always include a failure handler in your AJAX transactions

In this walkthrough you will add data input validation rules to the contact form.

 Insert contact records into the WebSQL database

 Set the values of form fields  Update contact records in the

WebSQL database

 Programmatically load pages

Steps

Open the Project

1. Open Intel XDK New

2. Click on the word PROJECTS in the top-left corner of the GUI. 3. Click the Open a Project button.

4. Select the following file:

/ftIntelXdkNew/walk/walk5_3/walk5_3.xdk

Add Disabled Lat/Lng Fields to the Form

5. Open contactform.html in Design mode.

6. Drag an Input widget from the Controls > Form palette and drop it directly underneath the beers select box on the design canvas. 7. Configure the following properties:

 Label: Lat (unchecked)  Placeholder: Latitude  Name: lat

 id: lat

8. Drag an Input widget from the Controls > Form palette and drop it directly underneath the beers select box on the design canvas. 9. Configure the following properties:

 Label: Lng (unchecked)  Placeholder: Longitude  Name: lng

 id: lng

11. Open the index.html file in Code mode.

12. Refactor the ContactForm.submitForm() method as indicated below:

submitForm: function() {

var form = $("form#contactform"); var validator = form.validate(); validator.form();

if (validator.numberOfInvalids() == 0) { } else {

alert("Invalid data input"); }

}

13. Inside the if() block, use the form.serializeArray() method to serialize all of the form fields into a local variable named fields.

var fields = form.serializeArray();

14. Immediately after the code that you inserted in the last step, append the values of the disabled lat and lng fields to the fields array.

fields[fields.length] = { name: 'lat', value: $('#lat').val() }; fields[fields.length] = { name: 'lng', value: $('#lng').val() };

15. Immediately after the code that you inserted in the last step, invoke the FriendsWithBeerDB.writeRecord() method to transfer the data from the fields variable into your webSQL database.

FriendsWithBeerDB.writeRecord( 'friend', this.friendId, fields, function() { } );

16. Inside the writeRecord() callback function, use the alert() method to output a message to the user and then reload the contacts.html page.

17. Review your submitForm() method to ensure that it appears similar to the following:

if (validator.numberOfInvalids() == 0) { var fields = form.serializeArray(); fields[fields.length] = { name: 'lat', value: $('#lat').val() }; fields[fields.length] = { name: 'lng', value: $('#lng').val() }; FriendsWithBeerDB.writeRecord( 'friend', this.friendId, fields, function() { alert("Record Saved"); $.mobile.changePage('friends.html'); } ); } }

18. Save the file and test the application in the emulator. You should now be able to create new contact records!

Attach a tap event listener to the List Items in the Friends List

19. In the FriendsList.displayList() method, where indicated by the comment, attach a tap event listener to the list items.

$('#friendsList > li').bind('tap', function(e) { });

20. Inside the event handler, retrieve the numeric identifier in the list item and transfer its value to the ContactForm.friendId property.

$('#friendsList > li').bind('tap', function(e) {

ContactForm.friendId = this.getAttribute('data-value');

});

21. Immediately after the code that you inserted in the prior step, programmatically change the page to contactform.html

$('#friendsList li').bind('tap', function(e) { var ContactForm.friendId = this.getAttribute(

'data-value'); $.mobile.changePage('contactform.html');

});

22. Save the file and test in the emulator. Clicking on an item in the Friends list should now transfer control to the data entry form.

Load Data Into the Form

whether the value of the ContactForm.friendId property is null. loadRecord: function() { if (this.friendId != null) { } }

25. Inside the if() block, invoke the FriendsWithBeerDB.runQuery()

method to retrieve the record from the WebSQL friends table where the friendId is equal to the friendId stored in the ContactForm object. loadRecord: function() {

if (this.friendId != null) {

var sql = "select * from friend where id = {0}"; sql.format(this.friendId); FriendsWithBeerDB.runQuery(sql, function(records) { }); } }

26. Inside the runQuery callback function, loop through the properties of the first record that was returned from the database query, transferring the values from the query result into the form.

loadRecord: function() { if (this.friendId != null) {

var sql = "select * from friend where id = {0}"; sql.format(this.friendId);

FriendsWithBeerDB.runQuery(sql, function(records) {

var rec = records[0]; for (var i in rec) { $("#" + i).val(rec[i]); }

}); } }

27. Immediately after the for-loop that you entered in the prior step, refresh the beerId select menu.

$("#beerId").selectmenu("refresh", true);

Invoke the loadRecord() method

28. Inside the ContactForm.init() method, invoke the ContactForm.loadRecord() method.

init: function() { this.initialized=true; this.populateBeerField();

30. Test the application. You should now be able to edit existing contact records.

Unit Summary

 Intel XDK New and jQuery Mobile support all HTML5 form element types.

 jQuery Mobile replaces standard checkbox, radio button, and select field controls with controls that have been optimized for a mobile device.

 Native HTML5 form field validation is not supported by most mobile browsers.

 You can easily adapt the jQuery Validation Plugin to work with jQuery mobile.

 The jQuery Validation Plugin supports validating basic patterns including email address, required data input, string length, numeric input, and more.

 You can persist data in memory, transmit form information to an application server, or store it in WebSQL or HTML5 localStorage.

1. The name and id properties of an input field should always be identical (true/false)

2. Which method do you invoke in order to get the value of a form field?

3. Which method do you invoke in order to set the value of a form field?

4. You must call the refresh method of a text input field after changing its value (true/false)

5. Which method can you invoke to easily combine the values from all of your form fields in order to transmit them to a server?

6. What are the relative advantages/disadvantages to storing information locally in WebSQL instead of posting it to an application server?

7. Describe how to populate a <select> control with options that are read dynamically from an application server.

In document (This page intentionally left blank) (Page 136-145)