Here are what i'm going to use:
SharePoint 2013
Javascript
REST Endpoint
SharePoint List (called: "Announcements")
WebSite (called: "example.com")
Refs:
http://www.plusconsulting.com/blog/2013/05/crud-on-list-items-using-rest-services-jquery/
https://msdn.microsoft.com/EN-US/library/dn292552.aspx
Very simply:
How do i INSERT a new item (row) inside the List please?
I tried:
$.ajax({
url: "https://example.com/_api/web/lists/getbytitle('Announcements')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify( { '__metadata': { 'type': 'SP.Data.AnnouncementListItem' }, "Title": "New Announcement!" } ),
headers: {
"Accept": "application/json;odata=verbose",
"Authorization": "Bearer " + accessToken
"X-RequestDigest": form digest value,
"IF-MATCH": etag,
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
Then i know a lot of things go wrong especially in headers section. But what does it mean by:
Authorization
accessToken
X-RequestDigest
IF-MATCH
.. and then HOW TO get these values (with JavaScript)? So that:
What are always the exact required fields there?
And how/where to get these values from?
I still can not find a simple and complete example about doing this Update / Insert properly.
So there are two ways that I have used to submit an item to a list, the jQuery library SPServices and REST API's. SPServices is really well documented here. Using REST API's is much faster and pretty easy too!
function createListItem(itemProperties, success, failure) {
$.ajax({
url: "https://example.com/_vti_bin/listdata.svc/Announcements",
type: "POST",
processData: false,
contentType: "application/json;odata=verbose",
data: JSON.stringify(itemProperties),
headers: {
"Accept": "application/json;odata=verbose"
},
success: function(data) {
success(data.d);
},
error: function(data) {
// failure(data.responseJSON.error);
alert("error");
}
});
}
First thing I am doing above is creating a function that you can call whenever you want to create a new list item. The parameter itemProperties can be populated with the fields which you need, see below.
var Title = "Title";
var Answer = "Answer";
var userid = _spPageContextInfo.userId;
var taskProperties = {
'Title': Title,
'Answer': Answer,
'UserId': userid
};
Then all we have to do is call this function with the new variable we just declared.
createListItem(taskProperties, function(task) {
alert("Thank you for your input!");
},
function(error) {
console.log(JSON.stringify(error));
}
);
Actually jsfiddle which you have posted in the previous commend is not the REST . you just use the SharePoint client object model. find below the REST API model I hope it will work
var cat = {
"__metadata": { "type": ItemType },
"Title": "GenIT-Issue",
}
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('Tickets')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(cat),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
},
error: function (data) {
}
});
I run this code inside my SharePoint page so there is no authentication required. it will run on current user privilege
Related
I am trying to create Firebase Dynamic Links with REST API using simple Javascript ajax code, but every time I am getting 400 bad request, though I have tried and implemented the documentation described at https://firebase.google.com/docs/dynamic-links/create-links. I couldn't find any solution for this.
Whats wrong I am doing here please help.
Here is my code
<!DOCTYPE html>
Change Content
<script>
function loadDoc() {
var params = {
longDynamicLink:
"https://thepary.page.link/?link=http://www.example.com/&apn=com.example.android&ibi=com.example.ios",
dynamicLinkInfo: {
domainUriPrefix: "https://thepary.page.link",
link: `https://threads-1511.web.app/threads/`,
iosInfo: {
iosBundleId: "com.bundleId",
iosAppStoreId: "1512677811",
iosIpadBundleId: "com.bundleId",
},
androidInfo: {
androidPackageName: "com.bundleId",
},
socialMetaTagInfo: {
socialTitle: `A thread by s`,
socialDescription: `s`,
socialImageLink:
"https://firebasestorage.googleapis.com/v0/b/threads-1511.appspot.com/o/playstore.png?alt=media&token=896f4fe6-2882-442e-b15c-3767d61b8a70",
},
},
suffix: {
option: "SHORT",
},
};
$.ajax({
url:
"https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[APIKEY]",
type: "POST",
data: params,
dataType: "json",
contentType: "application/json",
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
},
});
}
</script>
Since API expects contentType: "application/json",
You need to data: JSON.stringify(params)
After migrating various SharePoint 2013 JavaScript apps to SharePoint 2016, I had to look at an strange phenomenon of the SharePoint 2016 Rest API:
assume you have 2 ajax calls
Upload a file --> returns spFile
get the list item for the uploaded file --> returns spItem
jQuery.ajax({
url: "/sites/mysite/_api/web/getFolderByServerRelativeUrl('/sites/mySite/myLibrary')/files/add(overwrite=true, url='test1.txt')",
type: "POST",
data: params.arraybuffer,
processData: false,
headers: { "Accept": "application/json;odata=verbose", "X-RequestDigest": params.digest, "X-HTTP-Method": "POST","If-Match": "*" },
success: function (file) {
//get listItem for uploaded file
jQuery.ajax({
url: file.d.ListItemAllFields.__deferred.uri,
type: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: function (result) {
//after first upload: OK
var id = result.d.ID;
}
});
}
});
If the file has not yet existed under this URL, everything is OK. SharePoint creates a new list item, and you will get the new item with the correct ID in the second call - lets assume we get ID 1.
If a file with the same name was already existing under this url and later it was deleted, SharePoint generates a new item with a new ID. This is as expected.
BUT: In this case, the SharePoint Rest API returns the wrong list item. Instead of the new created list item (ID 2), you will get the old deleted item with ID 1.
In SharePoint 2013, this error does not occur. In SharePoint 2016 - this error only occurs in case of the same browser context for ajax call 1 and ajax call 2. Typically you are affected by this error, if you upload a file und at the same time you will update some meta values.
It seems to be a bug in SharePoint 2016. I suppose, MS have implemented a more strictly cache algorithm and was getting over the target.
Until MS will fix this bug, I have found a workaround:
Upload your file under a temporary name - jQuery.Guid.New() + myExtension
get the new item for your uploaded file
send a call to delete an possibly existing file with the real target name
rename your uploaded file into the real target name
var real_filename = 'test1.txt';
var temp_filename = jQuery.Guid.New() + '.txt';
// upload temp_filename instead real filename - fixes SharePoint 2016 ZombieId CacheBug
jQuery.ajax({
url: "/sites/mySite/_api/web/getFolderByServerRelativeUrl('/sites/mySite/myLibrary')/files/add(overwrite=true, url='" + temp_filename + "')",
type: "POST",
data: params.arraybuffer,
processData: false,
headers: { "Accept": "application/json;odata=verbose", "X-RequestDigest": params.digest, "X-HTTP-Method": "POST","If-Match": "*" },
success: function (file) {
//delete a possiblly existing file with real target name
jQuery.ajax({
url: "/sites/mySite/_api/web/GetFileByServerRelativeUrl('/sites/mySite/myLibrary/" + real_filename + "')",
type: "POST",
processData: false,
headers: { "Accept": "application/json;odata=verbose", "X-RequestDigest": params.digest, "X-HTTP-Method": "DELETE", "If-Match": "*" },
success: function () {
//target file was existing
finalize(file);
},
error: function () {
//target file was not existing
finalize(file);
}
});
}
});
function finalize(file) {
//get listItem for uploaded file
jQuery.ajax({
url: file.d.ListItemAllFields.__deferred.uri,
type: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: function (result) {
var spItem = result.d;
//rename the uploaded file
jQuery.ajax({
url: spItem.__metadata.uri,
type: "POST",
data: JSON.stringify({ __metadata: { 'type': spItem.__metadata.type }, FileLeafRef: real_filename }),
headers: { "Accept": "application/json;odata=verbose", "X-RequestDigest": params.digest, "content-type": "application/json;odata=verbose", "X-HTTP-Method": "MERGE", "If-Match": "*" },
success: function () {
//file was renamed
spItem.FileLeafRef = real_filename;
defer.resolve(spItem);
},
error: function (e) {
//something went wrong
defer.resolve(null, e);
}
});
}
});
}
I'm trying to update a file using the Github v3 api. Most of the documentation I could find was based on the older API. I want to utilize: https://developer.github.com/v3/repos/contents/#update-a-file
I first grab the file using:
$.ajax({
url: "https://api.github.com/repos/"+owner+"/"+repo+"/contents/"+path,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "user" + btoa(owner+":"+passwrd));
},
type: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
var jsonFile = data.content;
sha = data.sha;
var decodedJson = atob(jsonFile);
var parsedDecodedJson = JSON.parse(decodedJson);
parseData(parsedDecodedJson);
},
error: function(error){
alert.addClass('alert-danger').removeClass('hidden').html('Something went wrong:'+error.responseText);
}
});
Which works perfectly.
After editing the file, I try to update the file.
On my submit I post the following using jQuery:
var postData = {
"message": "Update",
"content": btoa(obj),
"sha": sha,
"branch":"gh-pages"
};
$.ajax({
url: "https://api.github.com/repos/"+owner+"/"+repo+"/contents/"+path,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "user" + btoa(owner+":"+passwrd));
},
type: 'PUT',
data: postData,
dataType: 'json',
contentType: 'application/json',
success: function (data) {
console.log("Success!!!", data);
},
error: function(error){
console.log("Cannot get data", error);
}
});
All the variables contain the expected values. Regardless, I keep getting a 404.
I know the API more often than not returns a 404 instead of something like a 403 as stated here: https://developer.github.com/v3/#authentication But it makes debuggin nearly impossible in my opinion. I have no clue what I'm doing wrong here. Thanks!
The only way I was able to do it is to make the entire round trip.
I used a javascript Github API wrapper
Luckily I found this article in which the bulk of the work was already been done. Props to Illia Kolodiazhnyi.
In the end. I ended up with this:
Handler on top of github api plugin
Usage:
var api = new GithubAPI({ token: token});
api.setRepo(owner, repo);
api.setBranch(branch).then(function () {
return api.pushFiles(
'CMS Update',
[
{
content: JsonData,
path: path
}
]
);
}).then(function () {
console.log('Files committed!');
});
I have been trying to send an email to the sharepoint user on click of a button in a client side web page.
I am trying to use the REST API using JSOM
and the code looks like below.
sendEmail("user#domain.com", "rec#domain.com", "test", "test-email");
function sendEmail(from, to, body, subject) {
var siteurl = _spPageContextInfo.webServerRelativeUrl;
var urlTemplate = siteurl + "/_api/SP.Utilities.Utility.SendEmail";
$.ajax({
contentType: 'application/json',
url: urlTemplate,
type: "POST",
data: JSON.stringify({
'properties': {
'__metadata': { 'type': 'SP.Utilities.EmailProperties' },
'From': from,
'To': { 'results': [to] },
'Body': body,
'Subject': subject
}
}
),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
alert("Eposten ble sendt");
},
error: function (err) {
alert(err.responseText);
debugger;
}
});
}
The issue what am facing here is:
1. Am getting an error 404 Not Found => does it mean my server does not have the utilities api?
2. When i tried (siteurl + "/_api/SP.Utilities.Utility.SendEmail") in browser it gives 404 not found.
Let me know how to resolve this issue.(Note: i dont have access to central admin).
(or)
Is there any other way to send an email without using workflow? or to call an workflow from a script?
Add following code to send E-Mail through Rest API in SharePoint.
Code get from this Link
$.ajax({
contentType: 'application/json',
url: urlEmail,
type: "POST",
data: JSON.stringify({
'properties': {
'__metadata': { 'type': 'SP.Utilities.EmailProperties' },
'Body': 'Lorem ipsum dolor sit amet...',
'To' : { 'results': ['admin#codeplayandlearn.com'] },
'Subject': "E-Mail From REST API";
}
}),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
alert("Email Send Successful.");
},
error: function (err) {
alert(err.responseText);
}
});
Want to integrate Paypal with my mobile web application. I tried to get the access token using client id and secret id but unable to get the access token.
Below is the sample Ajax call with I am making to retrieve the access token.
function getAccessToken(){
$.ajax({
url:"https://api.sandbox.paypal.com/v1/oauth2/token/",
type:"POST",
data : {"grant_type":"client_credentials"},
beforeSend: function (request)
{
request.setRequestHeader("Accept", "application/json");
request.setRequestHeader("Accept-Language", "en_US");
request.setRequestHeader("Authorization", "abc XXXXX:XXXXXXXXXXXXX");
},
success: function(data) {
alert(data);
},
error: function(e, messgae,type){
alert("Error" + e +" "+messgae+" type "+type);
}
});
I am unable to retrive the access token from the server.
Can anyone please tell me how can I integrate Paypal with my mobile web application using java script?
after a series of try and fail I found the correct AJAX call:
$.ajax({
headers: {
"Accept": "application/json",
"Accept-Language": "en_US",
"Authorization": "Basic "+btoa("**<Client ID>:<Secret>**")
},
url: "https://api.sandbox.paypal.com/v1/oauth2/token",
type: "POST",
data: "grant_type=client_credentials",
complete: function(result) {
alert(JSON.stringify(result));
},
});
You need to replace Client ID:Secret with the one that you find on your Developer Dashboard, for example AxxhGDh:hudh-X-h8qi
Above example doesn't works, below works for me:
var parameter = {
"grant_type": "client_credentials",
"username": "<username>",
"password": "<password>"
}
$.ajax({
headers: {
"Accept": "application/json",
"Accept-Language": "en_US",
"Authorization": "Basic <your auth key>"
},
url: "https://api.sandbox.paypal.com/v1/oauth2/token",
type: "POST",
data: parameter,
complete: function (result) {
alert(JSON.stringify(result));
},
})