Sharepoint Rest Api calls` - javascript

I am making a simple website where I have to save some of my data to sharepoint list. I am using only html css js only. I need to make REST calls to Sharepoint APIs to post data on SP. I am trying to get data from my list(in SP) as follow:
$(document).ready(function() {
processListItems(hostweburl, 'ListName');
});
function processListItems(url, listname) {
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
}
It returns this response:
"{"error":{"code":"-2147024891, System.UnauthorizedAccessException","message":{"lang":"en-US","value":"Access denied. You do not have permission to perform this action or access this resource."}}}"
I am referencing only two scripts:
<script src="js/jquery-3.1.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js" type="text/javascript"></script>
It says I am unauthorised to access. Although I am having admin rights to my list. Please tell me how to fix this issue. Do I need any authorization header for ajax call to Rest Api? I am new to Sharepoint. Please Help!

I think that custom scripting is disabled by default in SPOnline. You may have to enable it. These links may help:
Access denied office 365 / SharePoint online with Global Admin account
http://vamsi-sharepointhandbook.blogspot.com/2015/07/turn-scripting-capabilities-on-or-off.html

When you are trying to pull items from a list, specify the URL up to items. See below line for syntax -
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('"+listName+"')/items",
// Rest of the code
});

Yes you would need a authorization header for your requests. So your headers should be like this:
headers: {
"Accept": "application/json; odata=verbose",
"Authorization": 'Bearer '+ **access_token**
}
access_token: You would need to acquire access token to make requests. You can use adal library provided by Microsoft for that.

Related

NetSuite Restlet Using jQuery

I am trying to access a NetSuite restlet using jQuery. Here is my code for that:
jQuery.ajax({
url: "https://rest.na2.netsuite.com/app/site/hosting/restlet.nl?script=270&deploy=1&searchId=customsearch_active_models",
type: "GET",
dataType: "json",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "NLAuth nlauth_account=ACCOUNT#, nlauth_email=EMAIL, nlauth_signature=XXXXXX, nlauth_role=ROLE#")
}
})
.done(function(data){
console.log(data);
});
When I check the "Network" tab in Chrome/FF it's giving me the following 401 response:
XMLHttpRequest cannot load https://rest.na2.netsuite.com/app/site/hosting/restlet.nl?script=270&deploy=1&searchId=customsearch_active_models. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.tracksandtires.com' is therefore not allowed access. The response had HTTP status code 401.
Am I not formatting the Authorization part correctly? I can't find any documentation on accessing a NetSuite Restlet via jQuery so I'm sort of shooting blind here. Should I just use vanilla javascript and not jQuery? Any help would be much appreciated!
Try using jsonp like this:
jQuery.ajax({
url: "https://rest.na2.netsuite.com/app/site/hosting/restlet.nl?script=270&deploy=1&searchId=customsearch_active_models",
type: "GET",
crossDomain: true,
dataType: "jsonp",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "NLAuth nlauth_account=ACCOUNT#, nlauth_email=EMAIL, nlauth_signature=XXXXXX, nlauth_role=ROLE#")
}
})
.done(function(data){
console.log(data);
});
More info:
How does Access-Control-Allow-Origin header work?
Basically don't
Although #adolfo-garza 's answer does show JSONP correctly you gain nothing by using a Restlet and you give up a login that can never be used for something sensitive. Basically you've put one of your Netsuite credentials out on the public internet. Nothing good can come of this.
This is one of the use cases for Suitelets. You create a Suitelet that has public access (available without login; audience all roles) and then you don't need authentication (though there are ways to rely on shopping session or checkout session authentication if you need filtering information by customer).
If you are just trying to test a real Restlet Use Case then you should use Node or some non-browser based application to do that.

(Spotify Web API) Create New Playlist - POST request returning 'Error 403 (Forbidden)'

Here is the link to the Web API notes on how to create a new playlist. https://developer.spotify.com/web-api/create-playlist/
As far as I understand, the POST requests the url https://api.spotify.com/v1/users/{user_id}/playlists. This is requested while passing the access token and data. The content type of the data being 'application/json'.
For some reason this is failing and returning a Error 403 (Forbidden) in the console.
Anything I'm missing?
//(playlistName, userId, accessToken) are passed to this.
var urlString = 'https://api.spotify.com/v1/users/' + userId + '/playlists';
var jsonData = {
"name": playlistName,
"public": false
};
$.ajax({
type: 'POST',
url: urlString,
data: jsonData,
dataType: 'json',
headers: {
'Authorization': 'Bearer ' + accessToken
},
contentType: 'application/json',
success: function(result) {
console.log('Woo! :)');
},
error: function() {
console.log('Error! :(');
}
})
Having tried your example, I get a 401 unauthorized when filling in bogus data. So you are authorized, but the API really does not grant you the rights (403 forbidden).
Please have a look at the authorization guide. I am pretty sure, your error is there. Especially have a look at scope. You might simply not grant enough power in the login. And therefore ending up with only public access, which does not include adding playlists.
I cite form the API docs:
To be able to create private playlists, the user must have granted the
playlist-modify-private scope.
https://developer.spotify.com/web-api/authorization-guide/

How to access Recurly API with AJAX?

I'm using a jquery ajax call to a recurly API endpoint, but I get cross-origin errors. From my understanding, this is because Recurly only returns results as XML... when I use JSONP to get around cross-origin errors, I get an error because it receives the XML data but expects JSONP. Pretty obvious. But I'm trying to understand how exactly can one use this API at all via AJAX calls. I've been successfully able to access the API with PHP, but unfortunately, for this project, I can't use any client-side code.
Even if I find some sort of middle-code solution to get the XML and convert it to JSON for my side to accept, I need to utilize the API for POST requests (creating accounts, subscriptions, etc.) so I would like to understand how to utilize the API properly.
Here is an example of my code:
$.ajax({
url: "http://[DOMAIN].recurly.com/v2/accounts",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + window.btoa("[API KEY]"));
},
crossDomain: true,
type: "GET",
accepts: "application/xml",
dataType: "application/xml; charset=utf-8",
success: function (data) {
console.log("SUCCESS:", data);
},
error: function(e){
console.log("ERROR:", e);
}});
Anyone with Recurly API experience have any tips/advice?
From https://docs.recurly.com/api/recurlyjs/jsonp_endpoints
$.ajax({
dataType: 'jsonp',
url: 'https://{subdomain}.recurly.com/jsonp/{subdomain}/plans/{plan_code}',
data: {
currency: 'USD',
},
success: function (data) {
// do stuff
},
}
You should not use the V2 API from the browser. Doing so risks exposing your private API key. If someone has your API key they can make calls charging customers, modifying subscriptions, causing all sorts of problems.
Look at the JSONP endpoints that Byaxy linked to.

Salesforce OAuth with REST API using Javascript

I have an app in my salesforce developer account that I want to allow my users to access from a remote app that I am building. I see that I must use OAuth2.0 to first authorize my users before they are allowed to access the salesforce data. At the moment I am trying to use the username-password OAuth flow described on salesforce.
Step 1) I request access token using username and password via the below code snippet
var password = 'userPassword' + 'securityToken'
$.ajax({
type: 'GET',
url: 'https://login.salesforce.com/services/oauth2/token',
contentType: 'application/json',
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader('grant_type','password'),
xhr.setRequestHeader('client_id', '<client_id_here>'),
xhr.setRequestHeader('client_secret', '<client_secret_here'),
xhr.setRequestHeader('username', 'username#location.com'),
xhr.setRequestHeader('password', "password")
},
success: function(response) {
console.log('Successfully retrieved ' + response);
//Other logic here
},
error: function(response) {
console.log('Failed ' + response.status + ' ' + response.statusText);
//Other logic here
}
});
My request, however, is failing with the following message:
1) OPTIONS https://login.salesforce.com/services/oauth2/token 400 (Bad Request)
2) XMLHttpRequest cannot load https://login.salesforce.com/services/oauth2/token. No
'Access- Control-Allow-Origin' header is present on the requested resource.
Origin http://localhost is therefore not allowed access.
I have seen some sources (here here here) mention that CORS is not supported in salesforce, and that another solution should be used. Some solutions I have seen are Salesforce APEX code, AJAX toolkit, or ForceTK.
In summary, I am looking to see if (1) there is a simple mistake that I am making with my above request to get the OAuth access_token (2) or if I need to do something different to get the access (3) is there a better way to login users and access their salesforce data from my connected app?
All and any help is appreciated!
You will need to handle the OAUTH part on your own server. This isn't just due to lack of CORS, there is also no way to securely OAUTH purely on the client-side. The server could really be anything but here is an example server written in Java using Play Framework which has a JavaScript / AngularJS client as well: http://typesafe.com/activator/template/reactive-salesforce-rest-javascript-seed
You can not make this request from JavaScript. You'll need to make a server side request. There are many implementations of this flow in PHP, C#, Java, etc.
I'm posting my ajax code here that has worked for me and this CORS error in console doesn't matter. If you see in network you will get the access token.
see the ajax code below.
function gettoken()
{
var param = {
grant_type: "password",
client_id : "id here",
client_secret : "seceret here ",
username:"username",
password:"password with full key provided by sf"};
$.ajax({
url: 'https://test.salesforce.com/services/oauth2/token',
type: 'POST',
data: param,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
success: function (data) {
alert(data);
}
});
}
I hope this will work for you perfectly.
I think you need to add the origin URL/IP in CORS setting as well in salesforce if you are making a request from Javascript app so it can get access to salesforce data.

$.post (to different domain) not working (node.js / express app on port 8081)

I receive the error POST https://thewebsite.com 400 (Bad Request) when using $.post that way:
$.post("https://website.com/blabla",
{
domain: "infoinfo.com",
room: "someInfo",
application: "someInfo",
ident: "someInfo",
},
function (data,status) {
alert("Data: " + data + "\nStatus: " + status);
});
I tried setting res.header('Access-Control-Allow-Origin', "*"); in my route but that didn't work.
Any ideas on how I could fix this?
Ps.: The server I am posting to is service website (xirsys.com), I am pretty sure they allow external domains already. I'll contact them during the day if I can't find a solution (I am using the jQuery post as they suggested :/
Try to add this to your AJAX call:
contentType: "application/json; charset=utf-8",
dataType: "json"
Another reason maybe because of the same origin policy:
In computing, the same origin policy is an important security concept
for a number of browser-side programming languages, such as
JavaScript. The policy permits scripts running on pages originating
from the same site to access each other's methods and properties with
no specific restrictions, but prevents access to most methods and
properties across pages on different sites.
You can find out more informations about this issue from MDN docs or doing some research on Google about this topic.
You can try to use $.axax() like this:
$.ajax({
type: 'POST',
url: "https://website.com/blabla",
data: {
domain: "infoinfo.com",
room: "someInfo",
application: "someInfo",
ident: "someInfo"
},
dataType: "json",
contentType: "application/json",
success: function (e) {
alert("Data: " + data + "\nStatus: " + status);
}
});
This is due to the Same-origin policy. All the browsers as a security measure would not allow any cross domain requests.
http://en.wikipedia.org/wiki/Same-origin_policy
Like in your case you are posting to thewebsite.com domain from a different domain. A work around is to use the jsonp (the server should support json padding) from the jquery.
Check these sites for more info
http://www.jquery4u.com/json/jsonp-examples/
http://en.wikipedia.org/wiki/JSONP
http://stackoverflow.com/questions/6871021/how-to-enable-cross-domain-request-on-the-server
SAMPLE REQUEST:
$.ajax({
url: "http://yoururl",
type: "POST",
crossDomain: true,
data: JSON.stringify(somejson),
dataType: "json",
success: function (response) {
alert("success");
},
error: function (xhr, status) {
alert("error");
}
});
SAMPLE RESPONSE IN PYTHON:
response = HttpResponse(json.dumps('{"status" : "success"}'))
response.__setitem__("Content-type", "application/json")
response.__setitem__("Access-Control-Allow-Origin", "*")
return response
The link I was posting to was actually not good. The service I am using updated the link in their API to reflect the right one.

Categories