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
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:'', error: function(){//handle errors here }, callback: function(){ //do whatever you want //you can access response text as "this.responseText" } }); } PhoneGap
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.
Download Android Source Code developed by my friend Ajay Sharma.
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.
ReplyDeleteMithilesh . . Its cool !! Keep it coming !
ReplyDeleteFantastic, a PhoneGap example that actually works.
ReplyDeleteKudos to you sir, and a kick in the pooper for the main PhoneGap site.
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
ReplyDeleteHi
ReplyDeleteDevi 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.
is it necessary we need a jsonp connection WSDL connection ?
ReplyDeleteHello Sadagopan
DeleteAs 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.
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
DeleteHello sandagopan
Deletecan 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
Web Console(15218): Uncaught SyntaxError: Unexpected token ) at file:///android_asset/www/index.html:1
Deletei'm getting this error in the log when ever i touch the tweets button in the device
DeleteI 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 ?
DeleteThanks
Sadaa
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 .
DeleteAnd 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 .
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"
DeleteI 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.
It was fantastic and well elaborated each and every points.
ReplyDeleteThanks and keep it up
sir.. i want to call sharepoint webservices with phonegap in iphone plz help me for that.
ReplyDeletecan any body show me the phonegap andriod app code to connect the server?
ReplyDeleteThe above example not working for my android app.and modification have to do ?please suggest me
ReplyDeleteHey guys in couple of days i will upload code for Android, so please wait .. ...
ReplyDeleteIts very helpful... I was looking for such a code... Thanks
ReplyDeletewill it work for Windows PHone in phonegap above example ?
ReplyDeleteHi 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 ...
DeleteThank u mithilesh, it is worked for phonegap with windowsphone.
Deletemithilesh now i am trying to consuming wcf service instead of webservice. is there any examples ? i hope, you will post the wcfservice with phonegap.
I tried your code for PhoneGap, I'm running into a cross-domain error, any ideas?
ReplyDeleteHello 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
ReplyDeleteI think you have missed to add * in PhoneGap.plist or Cordova.plist
DeleteThanx i fixed it....
Deletehi mithilesh,
ReplyDeletei 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
Thanks dear.
ReplyDeleteI got the output,
I tested on with android phoneGap
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
ReplyDeleteHello I need your help in the code would look like but invoking this web service
ReplyDeletehttp://www.webservicex.com/globalweather.asmx?op=GetWeather
thanks
Hey
Deleteyou 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 ...
Very Nice.... Very well explain...
ReplyDeleteThanks for sharing this article...
wat actually is the output of this web service after clicking on SEARCH TWEETS button???
ReplyDeleteIs it this:
Phonegap+androidapp crashes with hardware acceleration;i've created adroidapp.....
are these tweets or errors??
Please reply soon!
Its really urgent
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.
ReplyDeletefantastic. Thanks!!!
ReplyDeletehi, 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.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteHey 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
ReplyDeleteHi I am trying to download API, but couldn't , plz see following error , any suggestion?
ReplyDelete400
www.xuijs.com is currently stopped