I have some JavaScript (physical file located in /SiteAssets library) that should delete an item in a SharePoint list.
We have existing JavaScript code that retrieves data from the list - it looks like this:
(notice that since the JavaScript runs on a PDP in context of the current user, we don't need a specific access token for the request)
var data = $.ajax({
url: projSiteUrl + "/_api/lists/getbytitle('<listname>')/items,
type: "GET",
dataType: "json",
async: false,
headers: {
Accept: "application/json;odata=verbose"
}
});
So I thought that I could write similar code to delete an item from the list again. I read on https://msdn.microsoft.com/en-us/library/office/jj164022.aspx#HTTPOps that the REST endpoint of SharePoint supports the "normal" REST verbs, so I wrote this, using the DELETE HTTP verb.
var restUrl = spSiteUrl + '/_api/web/lists/GetByTitle(\'' + listTitle + '\')/items(' + itemId + ')';
jQuery.ajax({
url: restUrl,
type: "DELETE",
headers: {
Accept: "application/json;odata=verbose"
}
})
But I am getting a 403 (FORBIDDEN) when requesting.
I guess the question is: Am I wrong in assuming that the DELETE verb is supported?
Thanks :-)
Ok, so apparently I do need the digest when doing modifications - but not for simple data retrieval.
If I change my code to
jQuery.ajax({
url: restUrl,
type: "DELETE",
headers: {
Accept: "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*"
}
}).
... it works with a simple AJAX request using the REST HTTP verb DELETE :-)
Related
I was trying to make an audio player by starting with a play button. In my HTMl code i made a button:
Play
Then I used this code to make it play a song, but it doesnt seem to work.
document.getElementById('play').addEventListener('click', function() {
$.ajax({
url: 'https://api.spotify.com/v1/me/player/play',
type: 'PUT',
headers: {
'Authorization': 'Bearer ' + access_token
},
dataType: "json",
contentType: "application/json",
data: JSON.stringify({
"uris": ["spotify:track:"] + apiData.item.id,
"position_ms": apiData.progress_ms
})
});
});
apiData.item.id refers to the id of the currently playing track
apiData.progress_ms refers to the progress in milliseconds of currently playing track.
When I run my code and click on the play button, nothing happens. I don't know what I did wrong.
But I tried making a pause button by first making a button with an id called 'pause'. Then I did the following:
document.getElementById('pause').addEventListener('click', function() {
$.ajax({
url: 'https://api.spotify.com/v1/me/player/pause',
type: 'PUT',
headers: {
'Authorization': 'Bearer ' + access_token
},
dataType: "json",
contentType: "application/json",
data: JSON.stringify({
"uris": ["spotify:track:"] + apiData.item.id,
"position_ms": apiData.progress_ms
})
});
});
This is actually working! But I don't understand why the play button doesn't work and the pause button does.
Here is the documentation I used for both buttons:
https://developer.spotify.com/documentation/web-api/reference/player/start-a-users-playback/
https://developer.spotify.com/documentation/web-api/reference/player/pause-a-users-playback/
For the play button I got this error in the console log:
error 400
Can somebody help me out?
tl;dr: Working snippets at the bottom of this answer!
The uris field takes an array containing Spotify uris. This "uris": ["spotify:track:"] + apiData.item.id doesn't resolve to an array but to a string which is not what the endpoint awaits. Using [`spotify:track:${id}`] will work therefore.
This snippet shows the difference between the two.
console.log(["spotify:track:"] + id);
// Output with id = 1234: "spotify:track:1234" -> String
console.log([`spotify:track:${id}`]);
// Output with id = 1234: ["spotify:track:1234"] -> Array of strings
The reason the stop button works is that Spotify's pause endpoint doesn't use any of the data you passed in. The pause endpoint only has one optional query parameter called device_id. The data you passed along with it just gets ignored therefore. So the Ajax call for pause can be simplified as seen in the following snippets.
Here are two working snippets given that an access token is used that has the user-modify-playback-state scope authorized.
Play
$.ajax({
url: 'https://api.spotify.com/v1/me/player/play',
type: 'PUT',
headers: {
'Authorization': 'Bearer ' + access_token
},
dataType: "json",
contentType: "application/json",
data: JSON.stringify({
"uris": [`spotify:track:${apiData.item.id}`],
"position_ms": apiData.progress_ms
})
});
Pause
$.ajax({
url: 'https://api.spotify.com/v1/me/player/pause',
type: 'PUT',
headers: {
'Authorization': 'Bearer ' + access_token
}
});
I'm trying to convert the curl code from an API called TextRazor to jquery's AJAX because of a platform limitations. I have tried many solutions from similar questions by the community but can't seem to get any data back (through the alert dialog). If it matters
from the documentation calling the API looks like this:
curl -X POST \
-H "x-textrazor-key: YOUR_API_KEY" \
-d "extractors=entities,entailments" \
-d "text=Spain's stricken Bankia expects to sell off..." \
https://api.textrazor.com/
My current AJAX code looks like this:
$.ajax({
url: "https://api.textrazor.com/",
type: "POST",
dataType: 'json',
data: {
x-textrazor-key: "YOUR_API_KEY",
extractors: "entities,entailments",
text:"Spain's stricken Bankia expects to sell..."
},
success:function(data) {
alert(JSON.stringify(data));
},error: function(xhr) {
alert("<some error>");
console.error(xhr.responseText);
}});
here is the link to jsfiddle if it helps: jsfiddle.net
Thanks for your support!
I think you have to pass "x-textrazor-key: YOUR_API_KEY" as additional header
$.ajax({
url: "https://api.textrazor.com/",
type: "POST",
dataType: 'json',
beforeSend: function(xhr){xhr.setRequestHeader('x-textrazor-key', 'YOUR_API_KEY');},
data: {
extractors: "entities,entailments",
text:"Spain's stricken Bankia expects to sell..."
},
success:function(data) {
alert(JSON.stringify(data));
},error: function(xhr) {
alert("<some error>");
console.error(xhr.responseText);
}});
data: {
x-textrazor-key: "YOUR_API_KEY",
The data: bracket in jQuery means that you want to send that data as POST, while you need to send the API key as a header.
Add this field to your code (after URL or so):
headers: {"x-textrazor-key": "YOUR_API_KEY"}
This looks close to me, but you put the header into the POST body. I think it should be the below. (Note that you also need quotes around 'x-textrazor-key', since the dashes in it will otherwise be interpreted as subtraction.)
$.ajax({
url: "https://api.textrazor.com/",
type: "POST",
dataType: 'json',
headers: {
'x-textrazor-key': "YOUR_API_KEY"
},
data: {
extractors: "entities,entailments",
text: "Spain's stricken Bankia expects to sell..."
},
success: function (data) {
alert(JSON.stringify(data));
},
error: function (xhr) {
alert("<some error>");
console.error(xhr.responseText);
}
});
There could of course be other issues here. (E.g. perhaps the API doesn't support cross-origin requests.) You'll want to take a look at the network tab in your browser's developer tools to see what actually happens.
I am currently trying to get a simple demo going of a crud app using the public OData feed at http://services.odata.org/V4/(S(jskq43fsvrxbzaf2jzhboo13))/OData/OData.svc/Products
GET-ting data works, however I am unable to update the data by clicking the button, and get a 501 (Not Implemented) error. I believe it deals with the need to enable CORS. Please see my fiddle. Thanks in advance!
var requestSettings = {
url: "http://services.odata.org/V3/(S(ettihtez1pypsghekhjamb1u))/OData/OData.svc/Products(" + key + ")",
method: "POST",
headers: {
"X-Http-Method": "PATCH",
'accept': "application/json;odata=verbose"
},
'contentType': "application/json; charset=utf-8", //content-length not required
datatype: 'json',
data: JSON.stringify(values),
success: function updateSuccess() {
deferred.resolve();
alert("successful update");
},
error: function updateError() {
deferred.reject();
alert("un-successful update");
}
};
$.ajax(requestSettings);
I have a JSFiddle here:
https://jsfiddle.net/jf713jf/ybLg1b4h/4/
Consider to use DevExpress.data.ODataStore that provides logic to access OData service.
Since you're working with fourth version of OData service, the ODataStore constructor options would like that:
new DevExpress.data.ODataStore({
url: "http://services.odata.org/V4/(S(jskq43fsvrxbzaf2jzhboo13))/OData/OData.svc/Products",
key: "ID",
keyType: "Int32",
version: 4,
// To overcome the cross-origin issue
jsonp: true
});
Hope it helps.
I am facing the following problem, I am trying to build a small application to search within the Odata dataset from the KVK (dutch chamber of commerce) to retrieve data based on file numbers, ZIP codes or tradenames.
My ajax code looks like this:
$.ajax({
url: urls,
error: function(){console.log('FAILED!')},
headers:
{
"Content-Type":"application/json",
"ovio-api-key":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
},
dataType: 'jsonp',
complete: function(data) {
console.log(data);
}
});
the URL would like like this:
https://overheid.io/api/kvk?&filters[postcode]=3553BA&callback=jQuery110208921047365292907_1432134770039&_=1432134770040
The error I am getting:
The part I do not understand, when I try the exact same URL in a web rest client such as chrome's advanced rest client the result is exactly what I want:
Fixed this by changing the code to:
$.ajax({
type: 'GET',
url: urls,
error: function(){console.log('Gefaald!')},
headers:
{
"Content-Type":"application/json",
"ovio-api-key":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
},
dataType: 'json',
complete: function(data) {
console.log(data);
}
});
just had to add the 'GET' type.
to get SharePoint List dataI am having an issue accessing the REST server via the CSOM. I have tried this with both the CSOM and just using jQuery. Code examples and the associated errors below. Can anyone direct me to a working example or tell me what I am doing wrong?
This code is part of a SharePoint Hosted App and the list is just a list in the root web. The user has permission to access the list and the app.
CSOM Example:
Yields:
Fail! : App Web is not deployed for this app's request url http://mySharePointRootWebURL.local.
var data = new SP.RequestExecutor("http://mySharePointRootWebURL.local/");
data.executeAsync({
method: "GET",
headers: { "Accept": "application/json;odata=verbose" },
url: "http://mySharePointRootWebURL.local/_api/web/lists/getbytitle(\'MyLstName\')/items",
success: function (data) { console.log('success!'); },
error: function (p1,p2,errorMessage) { console.log('Fail! :' + errorMessage); }
});
I can see that this example is not hitting the root web at all (from the app / app web).
jQuery Example
Yields:
Resource interpreted as Script but transferred with MIME type text/plain: "http://mySharePointRootWebURL.local/_api/web/lists/getbytitle(\'MyLstName\')/items&…Query19104068602353800088_1379462071044&alt=json-in-script&_=1379462071045". jquery.js:9597
Uncaught SyntaxError: Unexpected token < items:1
fail! : Error: jQuery19104068602353800088_1379462071044 was not called
$.ajax({
url: "http://mySharePointRootWebURL.local/_api/web/lists/getbytitle(\'MyListName\')/items",
type: "GET",
beforeSend: function(xhr){
xhr.setRequestHeader('Accept', 'application/json;odata=verbose'); },
headers: {"Accept":"application/json;odata=verbose"},
success: function(data){ console.log("success"); },
error: function errHandler(p1,p2,errMessage){ console.log("fail! : " + errMessage); },
dataType: 'jsonp',
crossDomain: true,
data: {
alt: 'json-in-script'
},
});
This is working as far as accessing the REST server and returning data, the problem is that the headers are not being added at all (verified in Fiddler). Without the headers the data comes back in XML. If that's how it has to be I will work with it, I guess, but I'd prefer to get JSON.
Your code doesn't look right. Here's code that wors with the cross-domain library
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync(
{
url:
appweburl +
"/_api/SP.AppContextSite(#target)/web/lists/getByTitle('Contacts')/items" +
"?#target='" + hostweburl + "'" +
"&$select=Id,FirstName,Title,WorkPhone,Email" +
"&$orderby=Title,FirstName",
method: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: successHandler,
error: errorHandler
})