Sunday, 26 February 2012

Callling Web services in PhoneGap

Hello Friends!! Now a Days PhoneGap getting fame and used by a lots of developer. I have done my very first PhoneGap application and i want to share my experience, so  in this blog I am going to talk about PhoneGap and web services more frankly How to call a web service in PhoneGap or javascript?

 PhoneGap:
      It is a cross platform framework to develop mobile application using web technologies like - HTML,javaScript,css.

 Web Services:
      Web services are methods hosted and executed by server. Electronic devices use it to communicate to server.It remove the platform dependency of devices that means a device running iOS can communicate with a device running Linux/Mac etc.

I assume that you have installed the PhoneGap and created a demo application to test- How to call a web service using javaScript?If not please create a demo application or you may use your original application.
  
Now we are going to write code to call web services

Create a file named as xui-<version number>.js, paste api code from link http://xuijs.com/downloads/xui-2.3.2.js   place xui-2.3.2.js in desired folder inside www folder, you can creates a folder called api. I use api folder to put all apis at one place.You can include xui api as follow -

We have included api, now we need to write javaScript function to call web service, i am using a separate function because it will keep my code clean and clear and we can reuse it easily  or call on a particular event.

function callWebService(){
       //create url 
       var url = "http://search.twitter.com/search.json?q=PhoneGap&rpp=1";
       x$.data = {};
       x$("#search_tweet_button").xhr(url,{
          error: function(){alert("failed"+this.responseText)},
          callback: function(){
             var jsonResponse = eval("("+this.responseText+")");
             var tweets =  jsonResponse.results;
             if(tweets.length>0){
             x$("#tweet").html(tweets[0].text);
             }
           }
        });//end of xhr
    }//end of method

xhr(url,{ callback:{ }}); method is use to access web services, function defined in front of error will get called when some error occurred while processing the request in other words if response code is not 200 and callback will be called on success of request.If you will not specify callback then response text will be inserted in html element, in this case "search_tweet_button".

eval("("+this.responseText+")"); is used to get correct json object.

tweetsPage.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title></title>
    <script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
    <script type="text/javascript" src="api/xui-2.3.2.js"></script>
    <script type="text/javascript" charset="utf-8">
      function callWebService(){
        //create url 
        var url = "http://search.twitter.com/search.json?q=PhoneGap&rpp=1";
        x$.data = {};
        x$("#search_tweet_button").xhr(url,{
          error: function(){alert("failed"+this.responseText)},
          callback: function(){
             var jsonResponse = eval("("+this.responseText+")");
             var tweets =  jsonResponse.results;
             if(tweets.length>0){
                x$("#tweet").html(tweets[0].text);
             }
          }
        });//end of xhr
      }//end of method
    </script>
  </head>
  <body>
    <h1 style="color:green;">Tweets Page</h1>
    <div id ="tweet" style="color:blue;">tweet will come here</div>
    <button type="button" onclick="callWebService()"                 id="search_tweet_button">Search     Tweets</button>
  </body>
</html>

Note : set ExternalHosts value as * in PhoneGap.plist file other wise it may not work for you.




























Example of post request :
function callWebService(){
    var url = "http://example.com/webser/xyzWebService/?&contentId=170;
    x$.data = {};
    x$("#html_element_name").xhr((url),
       { method:'post',
         headers:{'Content-Type':'application/xml'},
         data:' PhoneGap ',
         error: function(){//handle errors here },
         callback: function(){
           //do whatever you want
           //you can access response text as "this.responseText"
         }
       });
   }

If you are setting  Content-Type then you should comment the default content- type value in xui.js it was giving error for me.If your is OK, ignore it.
if (method.toLowerCase() == 'post') {
   //req.setRequestHeader('Content-Type','application/json');
   ;
}
If this blog is useful, please leave your comments. bye bye!!

 Download  Android Source Code developed by my friend Ajay Sharma.