How to use jquery ajax and webmethod with sitecore - 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.

Related

Use sharepoint cross-domain javascript library to consume REST API from localhost

I try to consume the sharepoint rest API from an application deployed in localhost. The sharepoint site is hosted in Sharepoint 2013 online.
For that purpose I use the javascrpt cross domain library. I get an example here https://github.com/OfficeDev/SharePoint-Add-in-REST-OData-CrossDomain.
My application is a full static website and I don't have VS, so I tried to figure out the Add In authorization. I go to the _layouts/15/appinv.aspx page of my site to give the authorization of third party application:
app domain: localhost:8080
redirect url: http://localhost:8080 (pointless?)
permission request XML: <AppPrincipal><RemoteWebApplication ClientId="*" /></AppPrincipal>
When I go to my application, I'm authenticated with my account: the cookie is populated with the token in FedAuth and rtFa
I'm supposing that it should be enough to now consume the API:
var executor = new SP.RequestExecutor(addinweburl);
executor.executeAsync(
{
url:
addinweburl + "/_api/web/GetFolderByServerRelativeUrl('Shared%20Documents')"
,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function(e) {
alert('success');
},
error: function(e, c, d) {
alert('fail');
}
}
);
The error handler is called and the 1007 error code is sent. This is quite weird since this code is used when size is too important.
Any help is appreciated.
The library can't be used if the application is not deployed on the same sharepoint site domain...
I fallback to OAuth protocol in order to authenticate my client.
The following documentation was key to understand how to obtain an access token: https://github.com/wearearchitect/sharepoint-oauth-app-client/blob/master/docs/Credentials.md

Calling RESTful API Using Python on Google App Engine

I got some problems when calling RESTful webservice.
I'm running a Django 1.5 project on google app engine now.
And I make use of httplib in python to call a RESTful webservice.
All methods(PUT, GET, DELETE, POST) work well on my local Machine (python 2.7.5, Django 1.5).
However, the behavior is changed on GAE...
PUT (used to store the data which user edited his information on the sites.), POST method is work well.
The GET method sometimes can't get the latest results from webservice server (not google datastore, the data are stored in other database server, I use the GET method to fetch the data from that server).
The DELETE method is not working totally on GAE.
Here is my code:
import httplib
args = ""
headers = {"Accept":"application/json"}
conn = httplib.HTTPConnection(IP, 8080)
try:
conn.request("DELETE", Some_API_Method_Url, args, headers)
response = conn.getresponse()
res = response.read()
I can't figure out why this happened, hoping someone can help me :(
Thanks in advance!
UPDATED:
I just found why the DELETE method is not working based on this link.
I send an ajax request which type is delete in my js file to my Django backend with the following code:
$.ajax({
type:'DELETE',
url:'some_url',
data:JSON.stringify({'key':'value'}),
contentType: 'application/json; charset=utf-8',
dataType: "text",
success: function(data){...},
error: function(data){...}
});
It seems that the appspot doesn't allow the DELETE request with body(data).
so, I changed the type of the AJAX request to POST, and it works...

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 to access the web service in html page? Static site?

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

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","*");