Pages

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.

40 comments:

  1. It was awesome dude and also very well written.You must continue with your writing skills.It soon or later helps many people around the globe.

    ReplyDelete
  2. Mithilesh . . Its cool !! Keep it coming !

    ReplyDelete
  3. Fantastic, a PhoneGap example that actually works.
    Kudos to you sir, and a kick in the pooper for the main PhoneGap site.

    ReplyDelete
  4. Hi im developing phonegap in android platform (in eclipse), when i tried the above example it doesn't work, i searched for Phonegap.plist, but couln't find that file... Pls help me

    ReplyDelete
  5. Hi
    Devi Phonegap.plist file is for iOS developers in android this step is not required, just check, have you given permission for internet connection? If not, give it in AndroidManifest.xml file.

    ReplyDelete
  6. is it necessary we need a jsonp connection WSDL connection ?

    ReplyDelete
    Replies
    1. Hello Sadagopan
      As you can see in above post i have use xui not yui(JSONP) only syntax are matching, more frankly we do not need JSONP.

      According to my understanding wsdl file is required to know about API(Web services )syntax, so to know about services we need wsdl.

      Delete
    2. Thanks Mithilesh . I tried the same in android but im not getting it . in my project i have a web service hosted locally . i have fetch data from it . can you please help me with the same

      Delete
    3. Hello sandagopan
      can you tell me which error is coming? or please show error log, i can help you more. without modification this example was working on android, please share error log, i will try to find solution .... best of luck

      Delete
    4. Web Console(15218): Uncaught SyntaxError: Unexpected token ) at file:///android_asset/www/index.html:1

      Delete
    5. i'm getting this error in the log when ever i touch the tweets button in the device

      Delete
    6. I guess my internet is not working Mithilesh . I have given the permissions but still its not working . so maybe because of that you program was showing error i guess. can you help me in fixing internet ?

      Thanks
      Sadaa

      Delete
    7. Sorry for messing up your blog . if possible delete my comments :( :( . I found the error, no its my mistake i have not enabled my wifi connection .. i got the output " "HTML5 + JQuery Mobile + PhoneGap Mobile Website Development by MIHap: We are developing a HTML5 + JQuery Mobile ... http " i need to trim this . can you help me with this .


      And one more help. if i need to fetch data from my local web service (that runs on my local host ) how can i do it ?


      Thanks a lot for quick replies .. Nice tutorial though .

      Delete
    8. congrates sada , to fetch services from your local just put ip address of your local machine like - http://127.0.0.1:80/myservice?parameters ......... or you should check your ip address by using command "ifconfig"
      I don't think there is any other requirement ...... best of luck , one more thing make sure that you machine and mobile are using same LAN.

      Delete
  7. It was fantastic and well elaborated each and every points.
    Thanks and keep it up

    ReplyDelete
  8. sir.. i want to call sharepoint webservices with phonegap in iphone plz help me for that.

    ReplyDelete
  9. can any body show me the phonegap andriod app code to connect the server?

    ReplyDelete
  10. The above example not working for my android app.and modification have to do ?please suggest me

    ReplyDelete
  11. Hey guys in couple of days i will upload code for Android, so please wait .. ...

    ReplyDelete
  12. Its very helpful... I was looking for such a code... Thanks

    ReplyDelete
  13. will it work for Windows PHone in phonegap above example ?

    ReplyDelete
    Replies
    1. Hi Naresh i can't guarantee because i have not tested it on Window device but it should work, just you need to create one Window Phone application and test, Hope it will work.I request you to acknowledge it by one new comment. It will help other windows developer ...

      Delete
    2. Thank u mithilesh, it is worked for phonegap with windowsphone.
      mithilesh now i am trying to consuming wcf service instead of webservice. is there any examples ? i hope, you will post the wcfservice with phonegap.

      Delete
  14. I tried your code for PhoneGap, I'm running into a cross-domain error, any ideas?

    ReplyDelete
  15. Hello Mithilesh....I am using your code but having some problem running it . It shows an alert failedERROR whitelist rejection: http://search.twitter.com/search.json?q=PhoneGap&rpp=1, i don't what that means...plz suggest some solution @ utpalrim@gmail.com

    ReplyDelete
    Replies
    1. I think you have missed to add * in PhoneGap.plist or Cordova.plist

      Delete
    2. Thanx i fixed it....

      Delete
  16. hi mithilesh,
    i am trying to write code in phonegap with windows phone.but i am gettin bad request method please could you fine where i did mistake. please
    see here :
    http://social.msdn.microsoft.com/Forums/en-US/windowsazuredevelopment/thread/8d249fcf-7b9f-469f-bad2-e4adf27d6529

    ReplyDelete
  17. Thanks dear.
    I got the output,
    I tested on with android phoneGap

    ReplyDelete
  18. one of the best example i have ever come across.tomorrow is my interview and i hope this gonna help me a lot..wish me luck and thanx alot

    ReplyDelete
  19. Hello I need your help in the code would look like but invoking this web service

    http://www.webservicex.com/globalweather.asmx?op=GetWeather

    thanks

    ReplyDelete
    Replies
    1. Hey
      you can use GET or POST Method to get that data. Copy paste the following url in browser

      http://www.webservicex.com/globalweather.asmx/GetWeather?CityName=New%20york&CountryName=US

      Now you can see the response. Now What you need to search is - how to parse xml data?

      Note: I have not checked it in code, so please go ahead and try it ...

      Delete
  20. Very Nice.... Very well explain...
    Thanks for sharing this article...

    ReplyDelete
  21. wat actually is the output of this web service after clicking on SEARCH TWEETS button???

    Is it this:

    Phonegap+androidapp crashes with hardware acceleration;i've created adroidapp.....

    are these tweets or errors??
    Please reply soon!
    Its really urgent

    ReplyDelete
  22. Hi Mithilesh kumar, Thanks for sharing the url, I have one issue... I have a login screen and I need to post a data to a url and parse the json response to access the response(url) in phone gap. do you have any tutorials regarding this issue.

    ReplyDelete
  23. fantastic. Thanks!!!

    ReplyDelete
  24. hi, I tried this code but iam getting the error "x$ is not defined at file"file:///android_asset/www/index.html:12". Please help me. My internet is working properly but when iam pressing the button the error is throwing like this.

    ReplyDelete
  25. This comment has been removed by the author.

    ReplyDelete
  26. Hey i updated the twitter api to 1.1, but now it says "Bad Authentication Data" in the error. How to solve this problem. Can anyone help please. Thanks

    ReplyDelete
  27. Hi I am trying to download API, but couldn't , plz see following error , any suggestion?
    400
    www.xuijs.com is currently stopped

    ReplyDelete