March 12, 2009

AJAX and JSON. An example on the iPhone

Posted in iPhone development tagged , , , , , , , at 7:55 pm by tetontech

Since the iBlog example went away, it was too complex to understand easily, there has been a need for an example of how to do use AJAX and JSON together.  JSON is a great way to retrieve data from a server since the data is easily converted into one or more JavaScript objects.  The QuickConnectiPhone framework makes it very easy to make JSON requests and I have created an example called JSONDataExample that will be included in QC 1.5 Beta 4.

For the JSONDataExample application I found an open server that can serve up JSON strings.  It is a Yahoo! image description service.  I’ll use this service in this example.

To start with, here is the final product running in the emulator and launched from Dashcode.

A list of Thumbnail images built using JSON

A list of Thumbnail images built using JSON

The QuickConnectiPhone source code to accomplish this is very small.  As always we start with the mappings in the mappings.js file for which the code is seen below.  We first map the command pictures to a Business Control Function called loadPictureDataBCF.  This BCF is responsible for making our AJAX call.

mapCommandToBCF(‘pictures’, loadPictureDataBCF);

mapCommandToVCF(‘pictures’, displayPictureDataVCF);

Next we map the pictures command to a View Control Function, displayPictureDataVCF, that is responsible for updating the display based on the data retrieved from the service.  Having completed our mappings for the pictures command we can now create the two control functions.

The loadPictureDataBCF function is created in the functions.js file and makes use of the QuickConnectiPhone AJAX wrapper ServerAccessObject.  This wrapper is designed to make your use of AJAX as simple as possible.

The code below shows a new ServerAccessObject being created.  The constructor is passed the URL of the service without any parameters.

function loadPictureDataBCF(parameters){

var pictureService = new ServerAccessObject(http://search.yahooapis.com/ImageSearchService/V1/imageSearch’);

pictureService.getData(ServerAccessObject.TEXT, true,‘appid=YahooDemo&query=england&output=json’);

}


Once pictureService has been created it is now ready for use.  Since we are retrieving data from the server we use the ServerAccessObject’s getData method.  The three parameters are:

  1. The data type being requested (use text when requesting JSON)
  2. A boolean indicating if a forced refresh should be enforced (true means never used cached data)
  3. The query parameters to append to the URL
This code is all that is required to get data from a server or service.  The QuickConnectiPhone framework will handle all of the data passing and ensure that it gets passed to the displayPictureDataVCF View Control Function that was mapped earlier.
The displayPictureDataVCF is responsible for parsing the string into a JavaScript object and then updating the view.  The results parameter is a JavaScript array that contains the results of any and all calls to Business Control Functions.  It is an array because you can have any number of BCF’s mapped to a single command.  The framework executes them all and places each result in this results parameter.
Each result has a data attribute in addition to an error attribute and a few others.  This data attribute contains the JSON string requested in the BCF we saw earlier.  Since this JSON string contains all of the information we want we use the JSON library, included in QuickConnectiPhone, to generate a JavaScript object by calling JSON.parse.

function displayPictureDataVCF(results, parameters){

var dataObject = JSON.parse(results[0].data);

var resultSet = dataObject.ResultSet;

var overViewDisplay = document.getElementById(‘overView’);

overView.innerHTML = ‘Total Results: ‘+resultSet.totalResultsAvailable;

overView.innerHTML += ‘<br/>Results Retrieved: ‘+resultSet.totalResultsReturned+‘<hr/>’;

var allImageDescriptions = resultSet.Result;

var numImageDescriptions = allImageDescriptions.length;

var body = document.getElementsByTagName(‘body’)[0];

console.log(body);

for(var i = 0; i < numImageDescriptions; i++){

var anImageDescription = allImageDescriptions[i];

var aDisplay = document.createElement(‘div’);

aDisplay.className = ‘imgDisplay’;

body.appendChild(aDisplay);

var aThumbnail = document.createElement(‘img’);

aThumbnail.src = anImageDescription.Thumbnail.Url;

aDisplay.appendChild(aThumbnail);

}

}

Once we have the JavaScript object we iterate over all of the image descriptions, build elements to display the data and add them to the body of the page being displayed.  We are now done.

I hope this helps you see how to do JSON calls to a service using QuickConnectiPHone.

Advertisements

2 Comments »

  1. Gab said,

    Is this type of connection possible of connecting to a SQLite database in a server? If so, would I just replace the: http://search.yahooapis.com/ImageSearchService/V1/imageSearch with the url of my database?

    Thanks for your posts, they help a lot!

    • tetontech said,

      Gab,
      Is there an application server or a web service running on the server machine where the SQLite database resides? If there is then you would change the URL to point to the application or the service. There isn’t a way to connect directly to the SQLite database.

      Lee


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: