Consuming Web Services by AJAX directly - javascript

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.

Related

Html cloud storage?

I'm trying to make an app using phonegap, but what I want to know is if it is possible to store information online. For example, say there is a number variable, and it is added to when a button is pushed. Could that value be saved somewhere and then a totally different device can retrieve the variable?
I looked at databases, but I couldn't really understand it. I want something that can be accessed by any device as long as It has a key or something.
Is this possible? If so, how would I do it?
PhoneGap uses JS so you cannot connect to the database directly. You should create a Web service using server side languages like PHP on external server and make ajax request on your web service. This approach is possible using PhoneGap.
Sample Code will look somewhere near:
function FetchData() {
$.ajax({
async: false,
type: "GET",
url: "Your_WebService_URL",
dataType: "json",
success: function(data) {
$.each(data, function(i, object) {
if(i==="title"){
document.getElementById("title").InnerHTML = object;
}
if(i==="home_image"){
document.getElementById("title").InnerHTML = '<img src="'+object+'"/>';
}
});
},
error: function() {
alert("There was an error loading the feed");
}
});
The web service, in this case json will throw the variables. May me somewhere like this :
[{"title":"my application"},{"home_image":"http://link.com/image.png"}]
I think this article is useful to you: Loading external data into a PhoneGap app using the jQuery JSONP plugin for cross-domain access. Also see this similar question here:
This is entirely possible.
You essentially need two components: the client interface, and the server.
The client displays the results to the users, and, using your example, waits for a button to be pushed. On the push of that button, the client would send a request to the server to increment the stored value (possibly through a jQuery.post, or get, function call).
The server page, written in php for example, receives this request, and accesses a file, or more realistically a database, to increment the value.
With some Googling, this should be very doable, but post specific questions if you get stuck.

AngularJS and WebSockets beyond

I just read this post, and I do understand what the difference is. But still in my head I have the question. Can/Should I use it in the same App/Website? Say I want the AngularJs to fetch content and update my page, connecting to a REST api and all of that top stuff. But on top of that I also want a realtime chat, or to trigger events on other clients when there is an update or a message received.
Does Angular support that? Or I need to use something like Socket.io to trigger those events? Does it make sense to use both?
If someone could help me or point me to some good reading about that if there is a purpose for using both of them together.
Hope I'm clear enough. thank you for any help.
Javascript supports WebSocket, so you don't need an additional client side framework to use it. Please take a look at this $connection service declared in this WebSocket based AngularJS application.
Basically you can listen for messages:
$connection.listen(function (msg) { return msg.type == "CreatedTerminalEvent"; },
function (msg) {
addTerminal(msg);
$scope.$$phase || $scope.$apply();
});
Listen once (great for request/response):
$connection.listenOnce(function (data) {
return data.correlationId && data.correlationId == crrId;
}).then(function (data) {
$rootScope.addAlert({ msg: "Console " + data.terminalType + " created", type: "success" });
});
And send messages:
$connection.send({
type: "TerminalInputRequest",
input: cmd,
terminalId: $scope.terminalId,
correlationId: $connection.nextCorrelationId()
});
Usually, since a WebSocket connection is bidirectional and has a good support, you can also use it for getting data from the server in request/response model. You can have the two models:
Publisher/Subscriber: Where the client declares its interest in some topics and set handlers for messages with that topic, and then the server publish (or push) messages whenever it sees fit.
Request/response: Where the client sends a message with a requestID (or correlationId), and listen for a single response for that requestId.
Still, you can have both if you want, and use REST for getting data, and WebSocket for getting updates.
In server side, you may need to use Socket.io or whatever server side framework in order to have a backend with WebSocket support.
As noted in the answer in your linked post, Angular does not currently have built-in support for Websockets. So, you would need to directly use the Websockets API, or use an additional library like Socket.io.
However, to answer your question of if you should use both a REST api and Websockets in a single Angular application, there is no reason you can't have both standard XmlHttpRequest requests for interacting with a REST api, using $http or another data layer library such as BreezeJS, for certain functionality included in various parts of the application and also use Wesockets for another part (e.g. real time chat).
Angular is designed to assist with handling this type of scenario. A typical solution to would be to create one or more controllers to handle the application functionality and update your page and then creating separate Services or Factories that encapsulate the data management of each of your data end points (i.e. the REST api and the realtime chat server), which are then injected into the Controllers.
There is a great deal of information available on using angular services/factories for managing data connections. If you're looking for a resource to help guide you on how to build an Angular application and where data services would fit in, I would recommend checking out John Papa's AngularJS Styleguide, which includes a section on Data Services.
For more information about factories and services, you can check out AngularJS : When to use service instead of factory

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/

web services with phoneGap

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");
}
});

Resource based routing module used in a Node.js REST API service, or other useful modules for this type of service

We are building a service that exposes a REST Api to the clients and we are using jugglingdb to create the models and express as the server.. I was wondering if there are any modules that are useful when creating a RESTful API in node.js
I tried using restify but it seemed to be just a watered down version of express and seemed to lack some functionality i needed from express, so i switched to express.
EDIT: We have no front-end. So we are strictly a rest api service that just provides data for various clients
One approach to consider is to keep things light and simple. If you don't have a front end, you can use the Connect module alone instead of Express, which is built on Connect:
http://www.senchalabs.org/connect/
I had good luck with this approach with my Node.js RESTful API. I did end up with a few repeated patters, especially in parsing incoming post data at times. But I found the code snips were just too small to be worth putting into a module, and it offered me amazing flexibility in certain situations.
One more approach that worked very well for me: Post ALL of your data as JSON - not as post key/value pairs. Depending on your API's clients, you may be able to do this. My API client was jQuery AJAX calls from a web page. It's very easy to send a JSON post. The jQuery processData property allows this as follows:
$.ajax({
url: '/nodeAjaxHandler',
type: 'POST',
data: JSON.stringify(formVals),
processData: false,
dataType: 'json',
success: function(data) {
},
error: function(a, b, c) {
}
});
Now receiving the data in your Node server is as simple as waiting for the body text to load, then JSON.parse it into an object. Very readable and manageable. And when you change the data fields being posted and received, you don't need to change any of the interface code at all!
(And you can go one step further if you dare, and make the field names match your database field names - then you can consolidate even more code. This felt risky to me but worked brilliantly - I'm not sure what the down sides might be yet. I do escape all my field names as well as my column names in the mySQL queries.)
RESTfull API get and post data through HTTP protocol. A more progressive approach is to use WebSocket [Wikipedia] npm link. Try to play with Sails.js framework build on Express.js that use Socket.IO for flash data transfering
If you're using MongoDB (with mongoose):
http://benaugarten.com/node-restful/
https://npmjs.org/package/node-restful

Categories