web services with phoneGap - javascript

I am working on project and I will implement by HTML5, javascript and I will use phonegap to give me applications in multi platforms and I have database in my server.
I know two ways to connect to my database and phoneGap accept that way :
1:Jquery Ajax requests.
like in the tutorial
http://www.indiageeks.in/phonegap-jquery-ajax-example-jsonjavascript-object-notation-response/
2:java script like in the tutorial
http://simonmacdonald.blogspot.com/2011/12/on-third-day-of-phonegapping-getting.html
but I am wondering ,,, Can I use web services on this thing ?
for example : all services will be in my server and also the database and I will connect to the web services through (html or java script or Jquery ) page and the data return in XML file and display it in the page.
Does phoneGap accept that way ?
if yes i want any good tutorials that will help me

It is a little difficult to be specific without knowing your server technology...
You can GET/POST to URLs from javascript, so yes you can access a webservice.
I have typically used MVC WebAPI projects to allow my phonegap applications to interact with the server.
WCF webservices work as well. This is a good example: http://www.codeproject.com/Articles/132809/Calling-WCF-Services-using-jQuery
You would access them in exactly the same way as you would from a normal web application, with a couple of gotchas:
You need to allow the origin within the res/xml/config.xml file, to test you can allow all origins:
<access origin="*" />
Add this tag under the widget tag.
You must enable CORS on the web server.
I would expose/consume JSON from the webservice, this is a natural serialization format for javascript based applications, with built in serialize/deserialize functions.
You can also download the output of the webservice to a file on the device using:
Download files and store them locally with Phonegap/jQuery Mobile Android and iOS Apps

You can use below method for making JSON request
var apiurl = "your url";
$.ajax({
url : apiurl,
dataType : 'jsonp',
data : {
token : Token,
key : keyuser,
method : 'method_name'
},
success : function(data) {
// here all output come and do action
console.log("data is " + data);
},
failure : function() {
console.log("error");
}
});

Related

Hide API token from generated .cshtml page source code

I have a .cshtml page, where a click on a button calls an API
Currently, my JS code looks like :
var headers = {};
headers["Authorization-Token"] = '#Model.ApiToken';
$.ajax({
url: "my-url",
type: "GET",
headers: headers
});
However, if the end-user opens the browser console, goes to the Network tab, searches for the generated cshtml, he can see :
var headers = {}
headers[Authorization-Token] = 'my_token'
The token can be seen in clear text
I can't call my API without this header, as the call is immediately rejected if the header is not present.
Is there a way to hide it to the end-user, and if so, how ?
Thank you
It is better to keep the tokens outside the browser, one option is to store the token inside the cookie (encrypted of course). ASP.NET Core can handle that for you automatically. Or in the backend as part of the user session.
An perhaps better option is to look at using the Backend For Frontend (a.k.a BFF) pattern to secure SPA applications.
See
Backend For Frontend Authentication Pattern with Auth0 and ASP.NET Core
The BFF Pattern (Backend for Frontend): An Introduction
Securing SPAs using the BFF Pattern (once and for all)

Local storage using OpenUI5 and Apache Cordova

I'm building a mobile app using OpenUI5 and Cordova. This app consume OData services but must support full offline capabilities. There are many optiones to store data using Cordova such as LocalStorage, Web SQL or even FileWriter. Also I find that OpenUI5 framework offer jQuery.sap.storage to store data through LocalStorage but I can't take this option into account due to the limited storage capacity (5MB).
Is it possible to request the entire data model from the OData service and convert it into JSON model? Because if there is any way to accomplish this, I could write files for every entity in the model (and the metadata file) using the FileWriter and consume this model when the app goes offline.
Does anyone tried to do something like this?
Edited
Thanks for answering...
I'm using jumpifzero tips to set data from the OData services into the Json model, like this:
var sServiceUrl = "http://address:port/DataService.svc/";
var odataModel = new sap.ui.model.odata.ODataModel(sServiceUrl, true);
var jsonModel = new sap.ui.model.json.JSONModel();
odataModel.read("/Dates", {
async: false,
success: function (odata, response) {
jsonModel.setData({ Dates: odata.results });
}
});
this.setModel(jsonModel);
You can also read the odata for each entityset, with the .read method, without any filter. In the success function given to the read, you can put the JS objects in a JSON model.
You can make a layer that fills the JSON model from the odata when online and from localstorage when offline.
You have an option to create offline apps (CRUD) using offline Kapsel plugin (Cordova plugin developed by SAP) that comes with SAP Mobile Platform. You should buy license for SAP Mobile Platform.
You can find more information here: http://scn.sap.com/docs/DOC-58063
I don't suggest offline Kapsel plugin. It is not mature enough to use it and it is actually under development. Furthermore you would need an SMP server for offline feature.
I would rather say you should use a half-baked solution that you form according your needs e.g.: http://coenraets.org/blog/2012/05/simple-offline-data-synchronization-for-mobile-web-and-phonegap-applications/

$ajax webservice failing on webfarm scenario

I am working on asp.net web form project.
In particular scenario I want to set some session values when user check/uncheck checkboxes in javascript.
In JavaScript session is not accessible so I developed a web service and gives call the web service method and that web method will going to set the values to session.
here is my js web service call.
$.ajax({
async: false,
url: baseUrl + '/' + "WebServices/ExtraInfoWebService.asmx/MyWebMethod",
data: { hdnValue: $("[id$='hdnCCSarray']").val() },
success: gett
});
This webservice call works perfectly on development machine having single IIS server but fails on production environment where multiple IIS boxes. I observed carefully and found that this webservice call is not working on IE browser only.
Anyone has suggestion on this please let me know.
Thanks in Advance!!!
If you are running in a Web Farm this means that you cannot use the default session store mode (InProc) because the different nodes of the farm will not be able to synchronize the session values. You will need to use an out-of-process session mode. There are 2 available:
StateServer
SQLServer
You can read more about the different session state modes in this MSDN article.
Or even better: refactor your code so that it doesn't rely on any session at all. I find it a very bad design to have a web service which is not stateless.

Authenticating and fetching data from couchdb using jQuery

I have a web app served by cherrypy. Within this app, I would like to fetch some data from a couchdb server, preferably using jquery. I am having trouble to authenticate into the server. When using:
$.couch.login({
name: 'usename',
password: 'password',
success: function() {
console.log('Ready!');
}
});
It sends the login request to the cherrypy server, not the couchdb. According to this, I can use jquery.ajax settings and therefore I have tried using:
$.couch.login({
url: 'http://127.0.0.1:5984',
name: 'usename',
password: 'password',
success: function() {
console.log('Ready!');
}
});
but it does not seem to work.
Any ideas? In addition, can anybody point me to good tutorial or simple web app developed in a similar fashion, i.e. a "standard" web page (not a couchapp), which contains jquery that gets info from couch.
What you are currently doing is telling jquery.couch.js to login against that url. (It needs to POST to /_session)
I believe you need to set up the urlPrefix property on $.couch.
$.couch.urlPrefix = "http://localhost:5984/"; // run this before anything else with $.couch
Don't forget that inside a browser, JavaScript enforces the same origin policy. Since the HTML page is presumably not being loaded from port 5984, you'll have figure out some clever way around it, such as CORS or mod_proxy.

Consuming Web Services by AJAX directly

I'm currently developing a web-site for the public transportation system based on the Trafikanten API (http://reis.trafikanten.no/topp2009/topp2009ws.asmx)
The site has several functionalities though it's Web-Services. It is implemented done in .NET framework with SOAP format. But we need to consume it's functionalities in client side language like JavaScript to be able to display the information in web-page. Can anybody suggest some easy way to cope this scenario?
Provided you're using a LAMP stack:
I would write a PHP script using the nusoap (http://sourceforge.net/projects/nusoap/) libarary to consume the SOAP web service and return JSON to your JavaScript via an AJAX call.
Edit
It's even easier in .NET. Just right click on your project and choose Add a web service. Then you can access methods of the web service just as you would any other object. As far as using it in JS, you could implement create an ASP page that outputs the results in JSON format and then consume that using jQuery as you would with a LAMP stack. Although, with the post back abilities of ASP, you might be better off letting it do the heavy lifting in JS and consume the web services directly in your code file behind your view.
Hope that helps.
If the service doesn't support JSONP, which it probably doesn't as an ASMX service, you'll need to create a service proxy to run on your local web server. Then, use that local service to act as an intermediary that circumvents the browser's cross-domain limitation.
If you added a service reference to Top2009WS in your ASP.NET project, something like this could act as a server-side proxy for GetLines() for example:
[WebMethod]
public Line[] GetLines(int ID) {
var client = new Topp2009WS.Topp2009WSSoapClient();
client.open();
return client.GetLines(ID);
}
Then, you could call through the proxy like this on the client-side:
$.ajax({
url: 'Service.asmx/GetLines',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: '{"ID":' + 12345 + '}',
success: function(response) {
// Alerts the first result's "LineName"
alert(response.d[0].LineName);
}
});
See this post for more information on using jQuery to call the web service.
I've done it in the past as Jesse says but with .NET. I build an "composed service" or adapter service which then calls the other services. The composed service would communicate SOAP with the .NET services while your application would communicate JSON with your composed service.

Categories