View
 

PhoneGap Ajax Sample

Page history last edited by DarkwaveMD 2 months, 3 weeks ago Saved with comment

Introduction

This tutorial is meant for fledgling developers who are unwise to the wild world of the mobile web and have little to some experience in JavaScript, html and css. By the end of this tutorial, you will be able to make ajax calls within PhoneGap to the twitter api services and render the response being returned. No frameworks are needed for this tutorial - it is straight up bare bones JavaScript, html and css. However, you will need a way to build onto simulator/device therefore you will need the tools for the specific platform you're building for (eg, build.phonegap.com, android sdk, ios sdk, xcode, etc). You may want to checkout the getting started tutorials if you don't have those already. 

 

If you want the code, you may aquire it here: https://github.com/timkim/PhoneGap_Ajax_Sample

Note the branches on the repo - each branch correspond to the steps listed on this tutorial. 

 

Step One: Setting up our base index.html file

The index.html file serves as our entry point to our application so we're going to start coding here. Let's start with out with the very basic html tag structure:

 

<!DOCTYPE html>

<html>

    <head>

    <title>PhoneGap Ajax Sample</title>

    <script type="text/javascript" src="phonegap.js"></script>

        <script type="text/javascript">

             function appReady(){

             }

             document.addEventListener("deviceready", appReady, false);

        </script>

    </head>

<body>

     <div id="main">

     </div>

</body>

</html>

 

As usual, we have our basic html tag structure with nothing too crazy. Note that we have linked the PhoneGap.js file:

<script type="text/javascript" src="phonegap.js"></script>

 

And the event listener 'deviceready':

document.addEventListener("deviceready", appReady, false);

 

Basically what this is doing is making sure your application loads properly on device by firing the appReady function once PhoneGap has boot strapped itself. The appReady function is where we'll be putting our application code so we'll be filling that in next. 

 

Finally, the div with id "main" is where we'll be rendering out content. 

<div id="main"></div>

 

Step Two: Making the Ajax Call

Within our appReady function, we'll flesh it out with our ajax call:

function appReady(){

     var ajax = new XMLHttpRequest();

     ajax.open("GET","http://search.twitter.com/search.json?q=bacon",true);

     ajax.send();

 

     ajax.onreadystatechange=function(){

          if(ajax.readyState==4 && (ajax.status==200)){

               document.getElementById('main').innerHTML = ajax.responseText;

          }

     }

}

 

To make the ajax call, we have to make a XMLHttpRequest object. We'll assign ours to a variable called 'ajax':

var ajax = new XMLHttpRequest();

 

Now to point our ajax request to the right location. Note how the twitter url is structured - the q=bacon at the end indicates that we are searching for tweets containing the word 'bacon'. In addition, we'll set the last parameter in the ajax.open() function call to 'true' in order to make it an asynch response. This allows us to attach a function to detect when a response comes in. Once that is all set up, we'll send the request using ajax.send():

ajax.open("GET","http://search.twitter.com/search.json?q=bacon",true);

ajax.send();

 

An important point about using PhoneGap is because the browser is more or less running localhost on your phone, it acts as a server would in terms of http requests. What this means is that you can make requests to api end points that you normally couldn't access if this were meant to be deployed for a desktop setting. That's a pretty short blurb so if you're feeling extra adventurous, read this article to expand your mind on same origin policy: http://en.wikipedia.org/wiki/Same_origin_policy

 

Ok, now to set up that function that detects when a response comes in. We're going to assign our own function and attach it to the ajax.onreadystatechange. Within this function, we're going to check to ensure ajax.readyState==4 and ajax.status==200. By checking when the readyState equals 4, we know a new response has come in. In addition, checking when the status is 200 we will know if the request went through okay. To note, 200 is the ok status for http protocols.

ajax.onreadystatechange=function(){

     if(ajax.readyState==4 && (ajax.status==200)){

          document.getElementById('main').innerHTML = ajax.responseText;

     }

}

 

When our response comes in, we're going to get a reference to the "main" div and just populate it with the ajax.responseText like so:

document.getElementById('main').innerHTML = ajax.responseText;

 

Let's see what that looks like now:

It sure doesn't look pretty, but at least the information is coming in okay. In fact, the information is pure json from the service! So let's convert it to some good ole HTML. 

 

Step Three: Formatting the response

If we look closely at the ajax.responseText we'll see that it has the structure of the JSON like so:

{"results":[

     // each tweet will have a structure like so

     {"profile_image_url": "url_to_some_image",

     "from_user": "username"

     "text": "tweeted_text"},

 

     {"profile_image_url": "url_to_some_image",

     "from_user": "username"

     "text": "tweeted_text"},

     ...

     ]

}

 

We'll need to grab each profile_image_url, from_user, and text for each tweet so we'll parse through the results and then build up some HTML to be placed in the "main" div. First we're going to eval() the response coming back so it'll be interpreted as an object we can use. Then we'll build up the HTML by looping through the results and putting each tweet item into HTML form. Once that's done, we'll populate the "main" div with the HTML we just built up:

ajax.onreadystatechange=function(){

     if(ajax.readyState==4 && (ajax.status==200||ajax.status==0)){

          eval('var data = ' + ajax.responseText + ';');

          var theResults = data.results;

          var theHTML = '';

          for(var i=0;i<theResults.length;i++){

               theHTML += ['<div class="tweet">',

                           '<div class="avatar"> <img src='+theResults[i].profile_image_url+' /></div>',                                                         '<div class="tweet_content">',

                                '<h2>'+theResults[i].from_user+'</h2>',

                                '<p>'+theResults[i].text+'</p>',

                           '</div>',

                           '</div>'].join('');

          }

          document.getElementById('main').innerHTML = theHTML;

     }

}

 

Now let's see what that looks like:

Ahh, even better. Our twitter app has structure, but let's prettify it a bit. 

 

Step four: Adding style

Luckily for us, when we built our HTML we added in class names to the divs:

theHTML += ['<div class="tweet"',

               '<div class="avatar"> <img src='+theResults[i].profile_image_url+' /></div>',                                 

               '<div class="tweet_content">',

                    '<h2>'+theResults[i].from_user+'</h2>',

                    '<p>'+theResults[i].text+'</p>',

               '</div>',

          '</div>'].join('');

 

So we'll just add some quick css to make it look better:

.tweet {padding-bottom:5px;}

.avatar {float: left; height: 48px; width: 48px;}

.tweet_content {margin-left: 60px; min-height: 48px;}

 

And now:

 

Horray! We've just made a very simple app that calls Twitter! To grab the code for this tutorial, you can get it all at https://github.com/timkim/PhoneGap_Ajax_Sample or as a zip/tar file https://github.com/timkim/PhoneGap_Ajax_Sample/archives/step_four