Programming in HTML5 with JavaScript and CSS3: Access and Secure Data
- 8/25/2014
- Objective 3.1: Validate user input by using HTML5 elements
- Objective 3.2: Validate user input by using JavaScript
- Objective 3.3: Consume data
- Objective 3.4: Serialize, deserialize, and transmit data
- Answers
Objective 3.4: Serialize, deserialize, and transmit data
Data can be received and sent in many forms. In the preceding objective, JSON and XML were examined specifically. The notion of presenting JSON or XML data directly to users isn’t ideal. Users would appreciate receiving the data in a more usable or readable and meaningful way. For this, you need to have the data converted from an XML string or JSON string into something else. The concept of converting the data from one form to another is called serialization or deserialization.
With serialization, the data is put into a format for transmission. With deserialization, the transmitted data is converted into something that can be worked with, such as a custom object. In addition to working with string data, applications can work with binary data. An application might capture drawings or pictures on a canvas and send that data back to the server. The data needs to be serialized into a binary stream to achieve this.
This objective reviews the serialization, deserialization, and transmission of binary and text data. The ability to submit data via the HTML Form and sending data with the XMLHttpRequest object is also reviewed.
Sending data by using XMLHttpRequest
Sending data to the server is similar to receiving data. The code examples in the preceding objective used the XMLHttpRequest object to receive data. The XMLHttpRequest object itself is agnostic to sending or receiving. It can accomplish both tasks based on how the object is set up. To send data, the send method must have data passed into it, and that data can be transmitted to the endpoint specified in the URL of the open method. The following code sends the XML data to the server:
var xmlData = "<Person firstname='Rick' lastName='Delorme' hairColor='Brown' eyeColor='Brown' /> "; var xReq = new XMLHttpRequest(); xReq.open("POST", "/ReceiveXMLData.aspx", false); xReq.responseType xReq.send(xmlData);
When data is transmitted to the server, it needs to be serialized into a format that the URL endpoint can understand. If the endpoint is expecting XML, the data must be XML; if it’s expecting binary data, the data must be in a binary format.
Serializing and deserializing JSON data
The browser provides native support for working with JSON and XML. The JSON object is available for converting a JSON string to and from an object (serialize/deserialize). The following code shows how this is accomplished:
var person = { FirstName: "Rick", HairColor: "Brown" }; var jsonPerson = JSON.stringify(person);
The person object has been serialized into a JSON string that can be sent to an endpoint URL for processing. To return the person back to a person object from a JSON string, the object can be deserialized by using the parse method:
var req = new XMLHttpRequest(); req.open("GET", "MyJsonData.json", false); req.send(null); var jsonPerson = JSON.parse(req.responseText);
When this code runs, the person object is reconstructed from the JSON string.
Serializing and deserializing binary data
Capturing dynamic image data follows a similar pattern as with the other techniques reviewed. The key difference is now the responsetype property must be set to blob. The following code demonstrates retrieving a binary image object and deserializing it into the webpage:
var xReq = new XMLHttpRequest(); xReq.open("GET", "orange.jpg", false); xReq.responseType = 'blob'; xReq.send(null); var blob = xReq.response; document.getElementById("result").src = URL.createObjectURL(blob);
The XMLHttpRequest object’s responseType property has been set to blob. Then by using the response property to extract the binary data, the BLOB is passed to the URL.createObjectURL method. The createObjectURL method gives the img element a URL linking to the BLOB, and the image is displayed in the browser. For the inverse, the data can also be submitted to the server as soon as it’s serialized into a BLOB:
var xReq = new XMLHttpRequest(); xReq.open("POST", "saveImage.aspx", false); xReq.responseType = 'blob'; xReq.send(data);
Using the Form.Submit method
The form element of an HTML page is the area of the form that contains elements that are typically input controls to gather information from users. The form element contains an action attribute that tells the form where to submit its data. Submitting the data in this way submits the entire HTML page back to the server for processing. However, another available mechanism is to hook up to the form’s submit event and handle the submission through JavaScript. This is useful for submitting the form’s data through an AJAX request so that users don’t have to leave the current page while the request is being processed. The form element at its simplest is as follows:
<form id="signupForm" action="processSignUp.aspx"> </form>
The form in this case will post its data to the processSignUp server page for processing, which in turn should redirect users back to a confirmation page of some sort. The other option for handling the form’s submission is to wire up the event in JavaScript:
$("document").ready(function () { $("form").submit(function () { }); });
Iterating over all the form elements, capturing the data out of them, and constructing a query string for use with an AJAX call would be possible inside the click event. The following code reviews this concept:
$("form").submit(function () { var fName = $("#firstName").val(); var lName = $("#lastName").val(); var qString = "Last Name=" + lName + "&First Name=" + fName; $.ajax({ url: 'processSignUp.aspx', type: "POST", data: qString, success: function (r) { } }); return false; });
The data from each field in the form is extracted and concatenated into a query string to submit to the server from the AJAX call. Although this method is functional, it has some drawbacks. First, a form with many elements will cause this code to get long. As new elements are added, the code will need to be updated. There is another option in the form of a jQuery method called serialize().
Using the jQuery.serialize method
jQuery provides a seamless way to encode data from an HTML form by traversing the form that’s passed into it and looking for input boxes to construct and return a query string. Then the query string can be posted to the server for processing. The preceding code is rewritten like this:
$("form").submit(function () { var qString = $(this).serialize(); alert(qString); $.ajax({ url: 'processSignUp.aspx', type: "POST", data: qString, success: function (r) { } }); return false; });
In this case, the jQuery.serialize method handles the extraction of the data from all the input elements and creates the query string. The advantage of using this method—beyond saving a lot of code—is that the query string is also encoded.
The serialize method acts on any results from the selector that’s passed into the $() segment of the jQuery. However, the serialize method has some limitations that you should know about. Only successful controls are serialized—meaning, only controls that are in a valid state. For input controls such as check boxes and radio buttons, only the ones that are in a selected state are considered. For radio buttons, because the name attribute must be the same for them all to be considered in a radio button group, you would specify the value attribute to differentiate them in the query string:
<input type="radio" name="gender" value="m"/>Male <input type="radio" name="gender" value="f"/>Female
The jQuery.serialize method makes the code involved to generate a query string of the parameters from a form much simpler to create and less error prone.
Objective summary
- Browsers provide native support via the JSON object to work with serializing and deserializing JSON strings.
- The JSON.parse method deserializes a JSON string into an object, and the JSON.stringify method serializes an object into a JSON string.
- By setting the XMLHttpRequest responseType property to the value ‘blob’, you can retrieve binary data.
- By default, the form submit action sends the entire page to the server (based on the action attribute) for processing.
- Handling the submit event allows you to customize how the form data is posted to the server.
- The jQuery.serialize method provides a convenient shortcut to convert specified input controls into a query string.
Objective review
Which of the following code lines is the correct way create an object from a JSON string stored in a variable called jsonString?
- var o = JSON.split(jsonString);
- var o = JSON.stringify(jsonString);
- var o = JSON.parse(jsonString);
- var 0 = JSON.join(jsonString);
Which of the following code lines allows an XMLHttpRequest to return binary data?
- request.responseType = ‘binary’;
- request.responseType = ‘image/jpg’;
- response.type = ‘blob’;
- request.responseType = ‘blob’;
How do you control what’s sent to the server when submitting a form?
- Add a submit button to the form.
- Handle the submit event of the form.
- Specify the action attribute of the form element.
- Ensure that all elements on the form have a name.