REST API DELETE LIST ITEM - USE THIS CODE - sharepoint

Delete Items:
This Code will help to delete the item in list using REST API for SharePoint.
var SiteUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ListName')/items('" + courtids + "')";
$.ajax({
url: SiteUrl
method: 'DELETE',
headers: {
'X-RequestDigest': $('#__REQUESTDIGEST').val()
},
async: false,
success: function (data) {
alert("Delete success");
},
error: function (data) {
}
});

To delete item using REST API, the following example code for your reference.
<script src="http://code.jquery.com/jquery-1.12.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
var listName="listName";
var itemId=1;
$("#deleteItem").click(function(){
deleteItem(listName,itemId);
});
});
function deleteItem(listName,itemId){
var siteUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('"+listName+"')/items(" + itemId + ")";
$.ajax({
url: siteUrl,
type: "POST",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-HTTP-Method": "DELETE"
},
async: false,
success: function (data) {
alert("Delete success");
},
error: function (data) {
}
});
}
</script>
<input id="deleteItem" type="button" value="Delete Item"/>

You dont need to reinvent the wheel. You should use the pnpjs: a microsoft library which uses the rest api to perform actions on sharepoint.
PNPJS

Related

SHAREPOINT -Restrict duplicate Entry

Guys Required support for below scenario
i have one list for booking with date and time . i want to restrict the duplicate entry by date and time
i have tried the rest Api code but it's not working.. please support find below my code
i tried to check with one condition .. i need to check with two conditions
Please support
<script src="/Departments/WDCI/UIJP/PublishingImages/jquery-1.12.4.js" type="text/javascript"></script><script type="text/javascript">
function PreSaveAction() {
var check = false;
var listid = _spPageContextInfo.pageListId.replace('{', '').replace('}', '');
var DateId = $('input[id*="Date_Req"]');
$.ajax({
//replace the rest api to filter items based on your files
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists(guid'" + listid + "')/items?$select=ID,Req_Date,Req_Time,Title&$orderby=ID desc&$filter=Date_Req eq + DateId + ",
type: 'GET',
async: false,
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
},
success: function (data, textStatus, jqXHR) {
var count = data.d.results.length;
if (count < 2) {
check = true;
} else {
alert('Dear Employee,This Calander Year you have already applied for two Job Positions.So you are eligible to apply next year only');
ddwrt:GenFireServerEvent('__commit;__redirect={/SiteAssets/Thank%20You.aspx}')
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
})
return check;
}
</script>
<script src="jquery-1.12.4.js" type="text/javascript">
</script><script type="text/javascript">
function PreSaveAction() {
var check = false;
var listid = _spPageContextInfo.pageListId.replace('{', '').replace('}', '');
var DateId = $('input[id*="Date_Req"]');
$.ajax({
//replace the rest api to filter items based on your files
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists(guid'" + listid + "')/items?$select=ID,Req_Date,Req_Time,Title&$orderby=ID desc&$filter=Date_Req eq + DateId + ",
type: 'GET',
async: false,
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
},
success: function (data, textStatus, jqXHR) {
var count = data.d.results.length;
if (count < 1) {
check = true;
} else {
alert('Dear Employee,there is no slot available during this period');
ddwrt:GenFireServerEvent('__commit;__redirect={/SiteAssets/Thank%20You.aspx}')
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
})
return check;
}
</script>
<script type="text/javascript">
function PreSaveAction() {
var check = false;
//var listid = _spPageContextInfo.pageListId.replace('{', '').replace('}', '');
var DateId = $("input[Title*='Req_Date']").val();
var TimeID= $("select[Title*='Req_Time'] option:selected").text();
alert(DateId);
alert(TimeID);
$.ajax({
//replace the rest api to filter items based on your files
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists//GetByTitle('Discussion2')/items?$select=ID,Req_Date,Req_Time,Title&$orderby=ID desc&$filter= Req_Date eq '" + DateId + "' and Req_Time eq '" + TimeID + "'", type: 'GET',
async: false,
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
},
success: function (data, textStatus, jqXHR) {
var count = data.d.results.length;
if (count < 1) {
check = true;
} else {
alert('Dear Employee,there is no slot available during this period');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
})
return check;
}
</script>```
You can use the following code to restrict duplicate entry:
<script type="text/javascript">
function PreSaveAction() {
var check = false;
//var listid = _spPageContextInfo.pageListId.replace('{', '').replace('}', '');
var DateId = $("input[title='Date_Req']").val();
alert(DateId);
$.ajax({
//replace the rest api to filter items based on your files
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists//GetByTitle('List0325')/items?$select=ID,Date_Req,Title&$orderby=ID desc&$filter=Date_Req eq '" + DateId + "'",
type: 'GET',
async: false,
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
},
success: function (data, textStatus, jqXHR) {
var count = data.d.results.length;
if (count < 1) {
check = true;
} else {
alert('Dear Employee,there is no slot available during this period');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
})
return check;
}
</script>
Note: you need to change the followings:
In var DateId = $("input[title='Date_Req']").val(), change "Date_Req" to your date column name;
In $.ajax(), change List title and columns' names to yours in url part
The result is like:

How to upload File to Azure Data Lake through Typescript REST CALLS

My problem was to upload the file from local directory to Azure Data Lake Store using Typescript only. I then found very useful REST API solution, I tested the REST API to perform all the required operations through postman and they worked fine, I then moved to Typescript to make these calls from typescript. Here is link to that: https://learn.microsoft.com/en-us/azure/data-lake-store/data-lake-store-data-operations-rest-api
To make REST CALLS through Typescript I'm using request-promise package, that I installed using npm install request-promise command. The documentation of this package is provided in this link:- https://github.com/request/request
But i'm able to perform all operations of the REST API i.e; Service-to-Service authentication, Creating Folder, Listing Folders, Rename File, Read File and so on. But i am not able to perform two operations/REST CALLS i.e; Upload File and Delete File, every time I make this call it gives Run Time Exception and error code 501 saying that this operation has not been implemented though i have tested these operations through Post Man and they work fine that way.
Is there any Access problem or what?
Here is the code of Typescript:
var fs = require('fs');
var request = require('request-promise');
var accessToken;
getAccessToken();
setTimeout(listFolders, 5000);
setTimeout(renameFile, 5000);
setTimeout(uploadData, 5000);
setTimeout(readData, 5000);
function getAccessToken() {
request(
{
method: 'post',
url: 'https://login.microsoftonline.com/067e9632-ea4c-4ed9-9e6d-
e294956e284b/oauth2/token',
form: {
grant_type: 'client_credentials',
resource: 'https://management.core.windows.net/',
client_id: 'dc9a4034-b03f-4974-9760-99541137a31c',
client_secret: 'mJ1Eba+sz0hXQko7gBN3D5WPDVLySCHXg4Mg5F4Ru4s='
},
json: true,
}, function (error, response, body) {
//Print the Response
accessToken = body.access_token;
console.log(accessToken);
});
}
function uploadData() {
fs.createReadStream('E:/accessToken.txt')
.pipe(request({
method: 'post',
url:
'https://bswadls.azuredatalakestore.net/webhdfs/v1/iModelAnalytics/abc.txt?
op=CREATE',
json: true,
headers: {
"Authorization": "Bearer " + accessToken,
}
},
function (error, response, body) {
console.log(response.status);
}
));
}
function readData() {
request(
{
method: 'GET',
url: 'https://bswadls.azuredatalakestore.net/webhdfs/v1/iModelAnalyti
cs/readFile1.txt?op=OPEN'
headers: {
"Authorization": "Bearer " + accessToken,
},
json: true,
}, function (error, response, body) {
//Print the Response
console.log("\n\nData = "+body);
//console.log(response);
}
);
}
function listFolders() {
request(
{
method: 'GET',
url: 'https://bswadls.azuredatalakestore.net/webhdfs/v1/
iModelAnalytics?op=LISTSTATUS',
headers: {
"Authorization": "Bearer " + accessToken,
},
json: true,
}, function (error, response, body) {
//Print the Response
console.log("************List Folders*****************\n ");
console.log(body);
}
);
}
function deleteFile() {
request(
{
method: 'PUT',
url: 'https://bswadls.azuredatalakestore.net/webhdfs/v1/
iModelAnalytics/readFile.txt?op=DELETE',
headers: {
"Authorization": "Bearer " + accessToken,
},
json: true,
}, function (error, response, body) {
//Print the Response
console.log("***************Delete File*****************\n ");
console.log(body);
console.log('Response= \n');
console.log(response);
}
);
}
function renameFile() {
request(
{
method: 'PUT',
url: 'https://bswadls.azuredatalakestore.net/webhdfs/v1/
iModelAnalytics/readFile1.txt?
op=RENAME&destination=/iModelAnalytics/readFile2.txt',
headers: {
"Authorization": "Bearer " + accessToken,
},
json: true,
}, function (error, response, body) {
//Print the Response
console.log("*************************Delete File*****************\n
");
console.log(body);
console.log('Response= \n');
console.log(response);
}
);
}
This is the error that I get:
Please share any thoughts regarding this.
Thanks a lot in advance.
PUT should be used to upload data whereas DELETE should be used to delete a file.
Append this &write=true to the query string when uploading data via pipe.
Try to change the code to:
function uploadData() {
fs.createReadStream('E:/accessToken.txt').pipe(request({
method: 'put',
url:'https://bswadls.azuredatalakestore.net/webhdfs/v1/iModelAnalytics/abc.txt?op=CREATE&write=true',
json: true,
headers: {
"Authorization": "Bearer " + accessToken,
}
}, function (error, response, body) {
console.log(response.status);
}));
}
function deleteFile() {
request({
method: 'delete',
url: 'https://bswadls.azuredatalakestore.net/webhdfs/v1/iModelAnalytics/readFile.txt?op=DELETE',
headers: {
"Authorization": "Bearer " + accessToken,
},
json: true
}, function (error, response, body) {
//Print the Response
console.log("***************Delete File*****************\n ");
console.log(body);
console.log('Response= \n');
console.log(response);
});
}

Accessing specific changeItem using Sharepoint REST API

I'm trying to get an individual change event using;
GET
* https://{sitecollection}/{personal/user_name_domain_onmicrosoft_com}/_api/web/getchanges('query')/item
Reference
http://msdn.microsoft.com/en-us/data/jj246759(v=office.12).aspx
And
http://msdn.microsoft.com/en-us/library/office/jj246759(v=office.15).aspx
I'm unable to get it working, and I can't find any example of this call.
I'm trying something like;
GET
https://{sitecollection}/{personal/user_name_domain_onmicrosoft_com}/_api/web/getchanges('Add=true,Item=true')/item
https://{sitecollection}/{personal/user_name_domain_onmicrosoft_com}/_api/web/getchanges(query='Add=true,Item=true')/item
but no luck.
FYI:: I'm not trying to get changelogs with this call. I'm trying to get an individual change item. But since the syntax is like that I put a random query in the those braces. The /getchanges(which is a POST call) works fine.
Any help on this?
There are at least two options how to construct request for a ChangeCollection endpoint:
Option 1
Post ChangeQuery via request body
function getChanges(webUrl,queryOptions,success,failure)
{
var changeQueryPayload = {
'query':{
'__metadata': { 'type': 'SP.ChangeQuery' },
}
};
for(var key in queryOptions) {
changeQueryPayload['query'][key] = queryOptions[key];
}
$.ajax({
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
data: JSON.stringify(changeQueryPayload),
url: webUrl + '/_api/web/getchanges',
success: success,
failure: failure
});
}
Option 2
Pass ChangeQuery expression via query string:
function getChanges(webUrl,queryOptions, success,failure)
{
$.ajax({
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
url: webUrl + '/_api/web/getchanges(#qry)?#qry=' + JSON.stringify(queryOptions) + ,
success: success,
failure: failure
});
}
Example
Retrieve updates for a web:
var queryOptions = {"Update":true,"Web":true};
getChanges(_spPageContextInfo.webAbsoluteUrl,queryOptions,
function(result){
var changes = result.d.results;
//print info
console.log('Found ' + changes.length + ' items');
},
function(error){
console.log(JSON.stringify(error));
});
Regarding requesting a specific change item, it could be retrieved from a results returned from REST service.
There is an example:
http://msdn.microsoft.com/en-us/library/office/dn499819(v=office.15).aspx
executor.executeAsync({
url: "<app web url>/_api/SP.AppContextSite(#target)/web/getchanges?#target='<host web url>'",
method: "POST",
body: "{ 'query': { '__metadata': { 'type': 'SP.ChangeQuery' }, 'Web': true, 'Update': true } }",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: successHandler,
error: errorHandler
});
Please refer https://msdn.microsoft.com/en-us/library/office/dn499819.aspx.
Following code is working for me.
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/getchanges",
type: "POST",
data: "{ 'query': { '__metadata': { 'type': 'SP.ChangeQuery' },'Web': true, 'Update': true, 'Add': true } }",
headers: { "accept": "application/json;odata=verbose", "content-type": "application/json;odata=verbose",'X-RequestDigest':$('#__REQUESTDIGEST').val() },
success: successHandler,
error: errorHandler
});
function successHandler(data, textStatus, jqXHR ){
alert("successHandler " + "textstatus:" +textStatus + "data: " + data);
}
function errorHandler(xhr, ajaxOptions, thrownError) {
alert('Request failed: ' + xhr.status + '\n' + thrownError + '\n' + xhr.responseText);
}

JQuery-UI copy paste issue works on second attempt

We are using following JQuery code (within JSF) to invoke Autocomplete. Everything seems to work fine when user keys in data but when user copies and pastes Autocomplete will be invoked on second attempt. I am testing following code in IE 8. Any inputs are appreciated
<pre>
<code>
<script type="text/javascript">
$(function () {
$(document).on('keyup.autocomplete','##{resp.workItemResponse.wiResponseId}', function() {
$('##{resp.workItemResponse.wiResponseId}').autocomplete({
minLength: 3,
source: function( request, response){
$.ajax({
type: 'GET',
url: "/iaportal/autoCompleteServlet",
cache: false,
delay: 200,
data: {
'respId':'#{resp.workItemResponse.wiResponseId}',
'type': '#{autoCompleteType}',
'term':request.term
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
response($.map(data.acctNum, function (item) {
return {
label: item.label,
value: item.label
}
}));
},
error: function(message){
alert("error "+message);
}
});
},
select: function( event, ui ) {
var selectedObj = ui.item;
var text = selectedObj.value;
$('.autoComplete#{resp.workItemResponse.wiResponseId}').attr('value', text);
$('.autoComplete#{resp.workItemResponse.wiResponseId}').trigger('change');
}
});
$('##{resp.workItemResponse.wiResponseId}').keyup(function(){
var text = this.value;
if(text == '' || text.length == 0){
$('.autoComplete#{resp.workItemResponse.wiResponseId}').attr('value', "");
$('.autoComplete#{resp.workItemResponse.wiResponseId}').trigger('change');
}
});
}); // on Ends
var textElem;
$(document).on('paste','##{resp.workItemResponse.wiResponseId}',function() {
textElem = this;
setTimeout(invokeOnPaste , 100);
});
function invokeOnPaste(){
var text = $(textElem).val();
if(text.length == 14){
$('.autoComplete#{resp.workItemResponse.wiResponseId}').attr('value', text);
$('.autoComplete#{resp.workItemResponse.wiResponseId}').trigger('change');
} else if(text.length != 0){
$('##{resp.workItemResponse.wiResponseId}').trigger('search','autocomplete');
}
}
});
</script>
</code>
</pre>

Dynamics CRM JavaScript: Can't update record because of CreatedOn?

I have the following to update a record:
var currentTimeBeingTracked = getCurrentTimeTracked();
if (currentTimeBeingTracked != null) {
currentTimeBeingTracked.dagency_EndDateTime = new Date();
var jsonTrackedTime = window.JSON.stringify(currentTimeBeingTracked);
$.ajax({ type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataPath + "/dagency_trackedtimeSet",
data: jsonTrackedTime,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
var newTimeTracked = data.d;
RetrieveTrackedTimes();
alert("Stopped tracking your time successfully.");
window.top.document.getElementById("contentIFrame").contentWindow.location.reload();
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
debugger;
alert("Couldn't stop tracking your time. " + XmlHttpRequest.responseText);
}
});
}
But I keep getting this message:
Error processing request stream. Error encountered in converting the
value from request payload for property 'CreatedOn' to type
'DateTime', which is the property's expected type. See inner exception
for more detail.
To create the record, I use the following code that works perfectly:
var trackedTime = new Object();
var timeEntryName = prompt("Please enter a name for the tracked time:", "New time entry");
if (!timeEntryName) {
return false;
}
var isBillable = confirm("Is this task billable? If Yes, press OK.");
trackedTime.dagency_name = timeEntryName;
trackedTime.dagency_StartDateTime = new Date();
trackedTime.dagency_Billable = isBillable;
var slot = new Object();
slot.Id = crmForm.ObjectId;
trackedTime.dagency_Slot = slot;
var jsonTrackedTime = window.JSON.stringify(trackedTime);
$.ajax({ type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataPath + "/dagency_trackedtimeSet",
data: jsonTrackedTime,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
var newTimeTracked = data.d;
RetrieveTrackedTimes();
alert("Started tracking your time successfully.");
window.top.document.getElementById("contentIFrame").contentWindow.location.reload();
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert("Couldn't start tracking your time. " + XmlHttpRequest.responseText);
}
});
What is the problem? Where can I find the inner exception the message refers to?
Changed to this and it worked correctly:
if (currentTimeBeingTracked != null) {
var trackedTimeUpdated = new Object();
trackedTimeUpdated.dagency_EndDateTime = new Date();
var jsonTrackedTime = window.JSON.stringify(trackedTimeUpdated);
$.ajax({ type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataPath + "/dagency_trackedtimeSet(guid'" + currentTimeBeingTracked.dagency_trackedtimeId + "')",
data: jsonTrackedTime,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
},
success: function (data, textStatus, XmlHttpRequest) {
var newTimeTracked = data.d;
RetrieveTrackedTimes();
alert("Stopped tracking your time successfully.");
window.top.document.getElementById("contentIFrame").contentWindow.location.reload();
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
debugger;
alert("Couldn't stop tracking your time. " + XmlHttpRequest.responseText);
}
});
}
What was wrong was that I need to set the X-HTTP-Method to MERGE and specify the guid in the URL.

Resources