Sharepoint How to do get request to external web service - ajax

How can I make get request from Sharepoint object model to external web service? I tried did it with ajax request:
$.get("http:/servername/webservice_name", function(data, status) {
alert("Data: " + data[0] + "\nStatus: " + status);
});
But I have an error: Access denied.
My web service has response in JSON format.
I have read a lot of article, but there are no decisions. I read, that ajax forbidden in SharePoint for external web service. How can I make it without ajax?

If you believe that the use of AJAX or a specific library is preventing you from accessing the web service, you can try invoking the web service directly using a native JavaScript XMLHttpRequest.
For example:
var verb = "GET";
var url = "http://servername/webservice_name";
var xhr = new XMLHttpRequest();
xhr.open(verb, url, true);
xhr.setRequestHeader("Content-Type","application/json");
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
myCallbackFunction(xhr.status, xhr.responseText);
}
};
xhr.send(data);
function myCallbackFunction(status, text){
// do something with the results based on the status
}
You should also confirm that your Internet Explorer settings are the same for SharePoint as they are for the HTML page where you're able to get the web service to work. Specifically, you'll want to check the browser mode and security settings.
Confirm that the problem still exists when the settings are identical before trying to troubleshoot your network or code.

In the SharePoint online it is work only for https web services. http from https web sites not allowed.
Final code, which work with https:
$(document).ready(function(){
$.ajax({
url: "https://services.odata.org/Northwind/Northwind.svc/Customers",
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
async: false,
success: function (data) {
if(data.d.results.length>0){
alert("Results Count:"+data.d.results.length);
}else{
alert("no data");
}
},
error: function () {
//alert("Failed to get details");
}
});
});

Related

How to enable CORS?

I'm making a request from client side to a web-API on different domain to extract data in JSON format. How do I enable Cross Origin Resource Sharing(CORS)?
Client runs on https while my web-API runs on http.
This is the AJAX call that I'm making :
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://map.techriff.in/api/values",
success: function (json) {
console.log(json);
},
error: function (err) {
console.log(err);
}
});
});
This site helped me when I had an issue with Chrome showing the following error: "No 'Access-Control-Allow-Origin' header is present on the requested resource"
Go down to the section titled "Enable CORS".
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Note, I used the following attribute syntax as opposed to what was listed in the site above:
[EnableCors("http://localhost:1616", "*", "*")]
You need to add the Access-Control-Allow-Origin: http://domain.com to your response header, where domain.com is replaced with the domain you want to allow (don't use * wildcards).
How you do this depends one your server stack. In ASP.NET:
Response.AppendHeader("Access-Control-Allow-Origin", "http://domain.com");
You then need to set $.support.cors = true in your jQuery to enable it on the client.
Add $.support.cors = true; somewhere before to make your $.ajax call.
Source: Is it safe to use $.support.cors = true; in jQuery?
Assuming you correctly set the Access-Control-Allow-Origin header on the server as well.
CORS jQuery AJAX request
First of all, this is a big issue. Everyone will say you have to enable CORS in the server. What if we are requesting an API?. What I did is.
Step 1: Make an ajax call to my own server.
Step 2: Make https request from my server to the API.
Step 3: Send the result to the ajax.
My AJAX call.
$.ajax({
type: "POST",
url: "makepay",
data:{
key:value
},
success: function(response) {
//place to handle the response
},
error: function() {
//place to handle the error
}
});
My server page
const https = require('https');
app.post('/makepay',function(req, res){
var options = {
host: "Site address",
path: "Path",
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
var req = https.request(options, (resp) => {
resp.on('data', (xmlresponse) => {
res.send(xmlresponse);
}}
req.write(parameters_to_the_API);
req.end();
});
I hope you will get at least the idea.

Plivo SDK call Recording

I am getting an error that i dont understand an cannot find any helpfull informations about:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https:*******' is therefore not allowed access. The response had HTTP status code 401.
function RecordTheCall()
{
var key = '*******************';
$.get( "https://api.plivo.com/v1/Account/"+key+"/Call/?status=live", function( data ) {
var callUuid = data.call_uuid
});
$.ajax({
url: "https://api.plivo.com/v1/Account/"+key+"/Call/"+callUuid+"/Record/",
type: "POST",
data: { 'auth_id': auth_id, 'call_uuid': CallUUID },
dataType: "json",
success: function (res) {
alert(res);
},
error: function(err) {
alert(err);
}
});
}
Call recording cannot be accomplished from the Web SDK directly. You cannot use the Plivo API from your Web browser using Javascript because cross-domain ajax requests are not allowed in browsers for security reasons.
This has been explained in this Wikipedia article. There are some work arounds to overcome this, but it is browser dependent and hence it might not work always. Instead you should use the Plivo XML/API in you application.

Angularjs and Web Api - JSON formatting issue

I have a lightweight Angularjs app and I'm trying to process json from my ASP.NET Web Api controller.
In the angularjs factory:
adapter.getLegacyCouriers = function(id) {
return $http({
method: 'GET',
url: 'http://legacywebapi.azurewebsites.net/api/legacycourier'
});
}
In the controller:
legacyService.getLegacyCouriers()
.success(function (response) {
alert("Success: " + JSON.stringify(response));
})
.error(function (response) {
alert("Error: " + JSON.stringify(response));
});
When I exchange the URL in the $http get with this one it hits the success block. However, my default URL which returns json formatted in the same way hits the error block.
Can someone help me? Both returns application/json response headers, and both return a status of 200 OK (using Chrome to debug). I can't figure out why my json is hitting the error block.
Your service responing with
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'run.jsbin.com'; is therefore not allowed access.
from your legacywebapi.azurewebsites.net/api/legacycourier
please see here jsbin.com/nugif/1/edit.
Just enable cross-origin resource sharing.

crossdomain $.ajax and 404 error

I want to retrieve some data using $.ajax from the external ASP.NET MVC site (in this case - from my site). The code below geive me a 404 Not Found error (of course the url is valid.
But, if I change the url from url: 'http://myurl.com/Home/GetMyCode/?id=mycode' to url: 'http://localhost:123/Home/GetMyCode/?id=mycode' everything is fine. So, how to fix it ?
$.ajax({
url: 'http://myurl.com/Home/GetMyCode/?id=mycode',
type: 'POST',
contentType: "application/json; charset=utf-8",
crossDomain: true,
success: function (res) {
...
},
error: function (jqXHR, textStatus, errorThrown) {
...
}
});
[HttpPost]
public JsonResult GetMyCode(string id)
{
try
{
return Json(new { result = "ok", resultData = "OK") });
}
catch (Exception e)
{
return Json(new { result = "error", resultData = "An error occured" });
}
}
Two Methods for Handling Cross-Domain Ajax Calls:
JSONP: The Current Standard for Cross-Domain Access
JSONP is a convention used by some sites to expose their content in a way that makes it easier for callers to consume data via script, even from an external domain. The trick consists in having the site return some JSON content not as a plain string but wrapped up in a script function call. For more details..
http://www.west-wind.com/weblog/posts/2007/Jul/04/JSONP-for-crosssite-Callbacks
http://www.jquery4u.com/json/jsonp-examples/
Cross-origin resource sharing (CORS)
To enable cross-domain requests in environments that do not support cors yet but do allow cross-domain XHR requests (windows gadget, etc), set $.support.cors = true;
You just tell jQuery that you're in an environment where Cross-Domain XHR requests are possible.
In order to retrieve data crossdomain, you probably need to use 'jsonp'
Looks like it might be a DNS issue. Are you able to get to: http://myurl.com ?
Is the .com domain you are trying to access publicly accessible? Or is it a loopback to localhost?
that tutorial worked for me, I had to implement the JSONP handling in my MVC project. http://www.codeguru.com/csharp/.net/net_asp/using-jsonp-in-asp.net-mvc.htm

How to do a simple http get ajax style using mootools 1.2.1

I'm trying to do a simple ajax GET that returns the html from google.com but with the following I keep hitting my onFailure. And when I hit status i get a 0, yet when I attempt to output the responseText I get nothing.
Anyone done a simple request like this in mootools 1.2.1?
function addSomeAction() {
el.onclick = function() {
var uri = "http://www.google.com";
var myRequest = new Request({
url: uri,
method: 'get',
onRequest: function(){
alert("loading...");
},
onSuccess: function(responseText){
alert("hi");
},
onFailure: function(responseFail){
alert("fail: " + responseFail.responseText);
}
});
myRequest.send();
}
}
Regardless of the framework used, you cannot do cross-domain AJAX requests. This is to prevent Cross-Site Request Forgery (CSRF) attacks and is a limitation imposed by the web browser.
Therefore, you can only fetch the HTML source of a page which on the same domain as the originating request.
There are specifications allowing for the asynchronous transfer of JSON data residing on another domain (JSONP), but they will not help you in this case.

Resources