How to access the web service in html page? Static site? - web-services

Accessing web service in HTML pages, i have a static site i want to access one web service in that site.

If you are running a static site I assume that the webservice you want to access is not on the same domain and you cannot set up a proxy on the server side. If both assumptions are correct you cannot use "ordinary" ajax because of the same origin policy in the browser. Your best bet may be JSONP as it is supported by many webservices.
I will give you a simple example. To retrieve a value stored under the key "mykey" from the openkeyval storage webservice in JavaScript with jQuery, call
$.ajax({
url: "http://api.openkeyval.org/mykey",
dataType: "jsonp",
success: function(data){
// do something with data
}
});
and to store a value, call
$.ajax({
url: "http://api.openkeyval.org/store/",
data: "mykey=myvalue",
dataType: "jsonp",
success: function(data){
// your value has been succesfully saved
}
});
Please note that nowadays many people consider Cross-origin resource sharing (CORS) a better alternative to JSONP. However, it may be a bit harder to get started for you.

Try Javascript, here is sample code
<html>
<head>
<title>Hello World</title>
<script language="JavaScript">
function InitializeService(){
service.useService(http://localhost/MyWebService.asmx?wsdl, "HelloWorldService");
service.HelloWorldService.callService("HelloWorld");
}
function ShowResult(){
alert(event.result.value);
}
</script>
</head>
<body onload="InitializeService()" id="service"
onresult="ShowResult()"> </body>
</html>

I agree with the answer provided by benedolph, but thought I might add ideas that go against his assumptions.
These steps may be more complex than you'd like, but really not terribly complicated - and would be cheap, if not free. But set aside at least one full day...
1) If you don't have one, get a domain to proxy the multiple services. Either free or as little as 5 USD per month (depending on your needs).
2) Write your proxy. This can be done in the language of your choice - Java (recommend Play framework), PHP (recommend CodeIgniter framework), Javascript (Node), Ruby (Rails), etc. What you'll do (from a high level) might look like:
- Read request. This would be a url you configure on the server app.
The url might look something like, "http://yourdomain.net/get/mashup/{service1:yourfirstservice.com, service2:yournextservice.com,...}.
- Parse the json into individual requests and load each of them from your server app. (The fastest way that I've found to complete this task is by using cURL's multi_init and multi_exec functions, via PHP. That said, Java and Ruby have equally powerful multi-threading capabilities).
- Put the results of each query into a json map.
- Once all responses come back, output the json response from your server and consume on your client side.
Anyway, that's what I'd do. Hope my response helps in one way or another!
-Brandon

Its so possible but you'll need some jquery, javascript, ajax for it

You can also use Jquery but the web service that you are accessing must reside on the same domain as the jQuery script that is making the request.It must comply the same domain policy.
$(document).ready(function() {
$('#Save').click(function() {
$.ajax({
url: "mydomain.com/test/ws/getData",
type: "POST",
dataType: "json",
data: "{BizName:'" + BizName + "'}",
contentType: "application/json; charset=utf-8",
success: function(msg) {
$('#status').html('Id: '+msg['d']['Id']);
},
error: function(e) {
$('#status').innerHTML = "Unavailable";
}
});
});
);

Related

Kendo ui webservice callback function

Have been following examples of calling a web service (GET request), and changing it slightly pointing it to my own service. The issue is that kendo appends a callback to the request address in the form of
...?callback=jQuery1910806812594877556_1375342185702&_=1375342185703
the web service fails to respond with an invalid arguments error, the issue being the & (ampersand). If you remove it, the service returns a response.
Is it possible to change the callback format on the kendo side to exclude it?
This _=1375342185703 is appended by jQuery.ajax which the Kendo DataSource uses under the hood. That thing is used as a cache buster (prevents browser caching). The fix is simple - disable jQuery caching:
transport: {
read: {
url: "your service",
dataType: "jsonp",
cache: true // enable caching which disables the cache buster
}
}

How do I authenticate and consume an external api with backbone?

I'm trying to create a very basic little backbone app that displays stats from my company's Harvest account. They have a REST API which authenticates via Basic Auth or oAuth. I seem to be faced with two problems here:
Authentication
Cross-origin requests
So I've started with setting the url for my collection to the respective url:
var Projects = Backbone.Collection.extend({
url: 'https://mycompany.harvestapp.com/projects',
});
And I've tried using this basic auth plugin but I can't tell if that part is working because I'm still getting Access-Control-Allow-Origin errors.
What's the best way to go about this?
This other StackOverflow question is similar and has more details that you should take a look at.
But the general idea is this, if you don't have access to the remote server (which I presume you do not with Harvest) then you need to perform the cross-site requests from your own server that you do control, most likely the one you are deploying this backbone app on. That means writing some server-side code (PHP, Node, etc.) to perform the requests (perfectly legal from server side) and then having your client (Backbone app) request from these scripts.
Here is a brief/pseudo-example with php:
request.php
<?php
echo file_get_contents('https://mycompany.harvestapp.com/projects');
?>
projects.js
var Projects = Backbone.Collection.extend({
url: 'request.php',
});

calling web service using jquery

I'm trying to call a local webservice/webApi using jquery, but I have been stuck for days. could somebody help me please.
So my webservice is sitting on localhost port 4011 i.e. localhost:4011/api/poi/
And my javascript is sitting on local host port localhost:4213/ and here is how I call it:
$.get('http://localhost:4011/api/values', function (data) {
alert(data);
});
When I enter the url into the browser directly, it returned the result. But when I'm calling it using the jquery. I have no response (by looking from the developer tools).
I'm not sure what I'm doing wrong. Please help.
I'm using webApi mvc .net4 if that helps.
This is due to the Same origin policy. Because the API is on a different port to where you're serving the web page the browser will not allow you to make the request.
You can use jsonp to get around this, or by using cross origin policy on your web service.
Use this if you are using a CrossDomain as CrossDomain doesn't work in jQuery!
$.ajax({
url: 'ajax/test.html',
crossDomain: true,
success: function(data) {
alert(data);
}
});
you might be restricted by the cross origin policy CORS. Configure your web service to accept the requests made from across the domain. You can add Access-Control-Allow-Origin headers like
responseMessage.Headers.Add("Access-Control-Allow-Origin","*");

How to use jquery ajax and webmethod with sitecore

I'm running Sitecore 6.4 and trying to get some data using ajax and webmethod in Sitecore. Everything is in a sublayout (user control)
This is the code that calls the webmethod:
$("#NextBanner").click(function () {
$.ajax({
type: "POST",
url: "/GetNext",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('success');
},
error: function (err) {
alert('error');
}
});
This is the webmethod, returns a string:
[WebMethod]
public static string GetNext()
{
return "Hello";
}
In a test project without using Sitecore I used "Default.aspx/GetNext" as the url for the ajax call but now obviously this doesn't work, I get 404 not found error because of the url.
What should the url be? The sublayout path is: /layouts/sublayouts/test.ascx
Any recommendation on a different approach of achieving this?
Thanks,
T
Update
Thanks everybody for the answers.
I ended up creating a web service under website/sitecore/shell/webservices, not sure if that's the right place to put the web service, any suggestions?
Thanks,
T
Put the code in a WebForm. You can't call a sublayout like a page. Reference the file by its file system path in your ajax call, e.g. /layouts/ajaxProcessor.aspx
You should also check out the following blog post about sitecore and ajax goodness: http://blog.velir.com/index.php/2011/09/22/lazy-websites/
Instead of using web methods, we'll typically make use of ASP.NET MVC controllers to serve JSON data in Sitecore projects. Properly setup, you can access some Sitecore.Context values (just not Item) and all Sitecore data access APIs.
http://www.sitecore.net/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2010/10/Sitecore-MVC-Crash-Course.aspx
http://shashankshetty.wordpress.com/2009/03/04/using-jsonresult-with-jquery-in-aspnet-mvc/
The Json() ActionResult option in MVC controllers makes sending back serialized data really easy.
I created a folder under 'Website' and placed my web services there.

Rails app making ajax calls to localhost when published on Heroku

I´ve developed an Rails app which works fine when running on localhost.
However, when pushing it to Heroku I run into problems with my ajax calls, which can look something like this:
$.ajax({
type: "GET",
url: "/getTemplatesForCategory/"+categoryId,
dataType: 'json',
success: function(data){
this.setState({templates: data, suppliers: []});
}.bind(this)
});
This is routed like this in my routes.rb:
get 'getTemplatesForCategory/:categoryId', to: 'templates#getTemplatesForCategory'
When these run on the Herou-version the console gives me this error:
Mixed Content: The page at 'https://myappname.herokuapp.com/templates/8' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://localhost:3000/getTemplatesForCategory/7'. This request has been blocked; the content must be served over HTTPS.
I´m using a Procfile which seems to work but I can't really figure out why the calls go to my localhost?
I discovered it was an completely different issue that caused this. Heroku did not pick up the changes to my javascript code so it was actually the old code make request to the localhost address.