Appcelerator Blog

The Leading Resource for All Things Mobile

Quick Tip: Sending arrays to web services

0 Flares 0 Flares ×

When you build forms in HTML and use checkboxes or multiple-selection lists, you know these two controls send data to the server as an array, which is then handled by the server as such.

With Titanium, you can build native mobile forms that POST the data to the server without requiring changes in the server code. Consider the following example of a Titanium app POSTing data to an existing back-end script:


var url = "http://www.yourserver.com/saveformdata.php";
var client = Ti.Network.createHTTPClient({
    onload : function(e) {
            alert('success');
     },
     onerror : function(e) {
         alert('error');
     },
         timeout : 5000
});

var payload={
    name    :"TheName",
    email    : "TheEmail"
}
client.open("POST", url);
client.send(payload);

Now, imagine that the back-end can also accept an array with a list of hobbies. You build your mobile user interface, gather the data and build your array. Then you try to send your payload like this and it doesn’t work.


var payload={
    name    :"TheName",
    email    : "TheEmail",
    hobbies    : [
        "skateboarding",
        "playing guitar",
        "walking on the beach"
    ]
}

This won’t work because when Titanium encodes the array it will not be in the format the server is expecting it. The proper way would be:


var payload={
    name            :"TheName",
    email            : "TheEmail",
    "hobbies[0]"    : "skateboarding",
    "hobbies[1]"    : "playing guitar",
    "hobbies[2]"    : "walking on the beach"
}

Notice that there’s a property for each of the elements of the array, and each value is provided as a simple string.

Hope this saves you some time when bringing your existing web services to mobile.

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Email -- 0 Flares ×

Sign up for updates!

Become a mobile leader. Take the first step to scale mobile innovation throughout your enterprise.
Get in touch
computer and tablet showing Appcelerator software
Start free, grow from there.
0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Email -- 0 Flares ×