This is the request that I am sending via javascript on a click of a button.
_crmProxy = "http://xxxxxxx:12355/dev_test/Service1.svc";
var name = "yz\\c.crm";
var pwd = "321#";
var text = "Parshu";
var response = null;
$.ajax({
async: true,
type: "POST",
headers : {
'Authorization' : 'Basic ' + btoa(name + ':' + pwd),
'Content-Type' :'application/json'
},
data: '{"userName": "' + text + '" }',
url: _crmProxy + "/WelcomeUser",
success: function (result) {
response = result.WelcomeUserResult;
},
error: function (error) {
alert("err");
}
});
but I am getting 401 Unauthorized OPTIONS error and couldn't go ahead. Can you please tell me where am I going wrong.
Thank you.
Prashant
Related
I have some problem with Getting workitems from tfs via the following javascript code:
var res = new XMLHttpRequest();
var body = "{'query' : \"select * from workitems where [Change Number] = 'CH-0000433' \"}" ;
res.open("POST","<SERVER_NAME>/tfs/InternalApplications/Testing%20Services/_apis/wit/wiql?api-version=1.0",true,<LOGIN>,<PASSWORD>);
res.setRequestHeader('Content-type', 'application/json');
res.send(body);
when I am trying to execute this script, I am getting the 401 - Unauthorized error
I`ve wrote the PowerShell analogue of this script, and it works fine:
$q2 = """select Id from workitems where [Change Number] = 'CH-0000433' """
$res = Invoke-WebRequest <Server_Name>/tfs/InternalApplications/Testing%20Services/_apis/wit/wiql?api-version=1.0 `
-ContentType application/json `
-Credential $(Get-Credential) `
-Method Post `
-Body "{'query' : $q2}" `
-UseBasicParsing
I suppose that in javascript case I am passing credentials incorrectly, so how should I change it?
I've tested on TFS 2017 with the code snippet below and it is working:
var jsonObj = [{
"op": "add",
"path": "/fields/System.Title",
"value": "cecetest1"
}];
$.ajax({
url: 'http://TFS2017:8080/tfs/DefaultCollection/ScrumProject/_apis/wit/workitems/$Task?api-version=1.0',
type: 'PATCH',
contentType: "application/json-patch+json",
data: JSON.stringify(jsonObj),
cache: false,
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("domain\\username" + ":" + "password"));
},
})
I am trying to update a sp list with the following javascript/ajax. It succeeds until it gets to the ajax function, which is where it fails. It says the ItemID is not defined, when it is defined as:
var ItemId=item.ID
Any help appreciated.
<script type="text/javascript">
function updateMultipleListItems(){
var listName="Address Validation";
//CustomerNumber.val("16");
var CustomerNumber="CustNum";
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?$select=ID&$filter=Cust_x0020_Number eq 17",
type: "GET",
headers: {
"Accept": "application/json;odata=verbose",
},
success: function (data) {
for (var i = 0; i < data.d.results.length; i++) {
var item = data.d.results[i];
alert("1");
var itemType = GetItemTypeForListName(listName);
alert("2");
var itemId = item.ID;
alert("3");
var item = {
"__metadata": {
"type": 'SP.Data.Address%20ValidationListItem'
},
"assign": "testinput"
};
alert("4");
$.ajax({
url:_spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items('" + ItemId + "')",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},
success: function (data) {
console.log('Update Success');
alert("Success");
},
// error: function(xhr, status, error) {
// var err = eval("(" + xhr.responseText + ")");
// alert(err.Message);
//}
});
}
},
error: function (data) {
alert("Error");
}
});
}
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>
What I'm trying to do:
I am trying to update all records in a list where the cust_number (a column in the list) field is 17 so that assign (another column) = "testinput".
eg:
Cust Number| Assign
17 | testinput
1 |
17 | testinput
I'm afraid you made a simple typo.
On a certain point in your code you declare the following:
var itemId = item.ID;
Later on you try to acces that same variable
url:_spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items('" + ItemId + "')",
However itemId != ItemId
Javascript is case sensitive.
I am new to SharePoint Online and REST API.
I am currently working on a SharePoint Add-In which creates folders in a document library residing in the Host Web and share the permission to specified external users. I am currently attempting to do everything using REST API.
I am successfully able to create the folders but I am currently unable to share the folders to external users.
I am having trouble resolving the following endpoints when attempting to use the host web context. The first endpoint below is for resolving the external email, and the second one is for performing the actual sharing of the folder to the external user.
[appUrl]/_api/SP.AppContextSite(#target)/SP.UI.ApplicationPages.ClientPeoplePickerWebServiceInterface.clientPeoplePickerResolveUser?#target='[hostUrl]'
[appUrl]/_api/SP.AppContextSite(#target)/SP.Web.ShareObject?#target='[hostUrl]'
I am getting the error 404 Not Found: Cannot find resource for the request SP.UI.ApplicationPages.ClientPeoplerPickerWebServiceInterface.clientPeoplePickerResoveUser. The same error occurs for SP.Web.ShareObject when I try to force it to run.
Below is the javascript that I am using
var ShareToRecipients = function(folder, recipient, appUrl, hostUrl){
var url = appUrl = "/_api/SP.UI.ApplicationPages.ClientPeoplePickerWebServiceInterface.clientPeoplePickerResolveUser";
url = WebComponents().getTargetUrl(url, hostUrl);
var sharedDocUrl = hostUrl + "/ExternalShareDocLib/" + foldername;
var checkUser = $.ajax({
url: url,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify({
'queryParams': {
"__metadata": {'type': "SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters"},
"AllowEmailAddresses": true,
"AllowMultipleEntities": false,
"AllUrlZones": false,
"MaximumEntitySuggestions": 50,
"PrincipalSource": 15,
"PrincipalType": 1,
"QueryString": recipient
}
}),
headers:{
"accept": "application/json;odata=verbose",
"X-RequestDigest": $('#__REQUESTDIGEST').val()
},
error: function(jqXHR, textStatus){
myapp.LogAPIError(jqXHR, textStatus)
}
});
checkUser.success(function(data){
var user = data.d.ClientPeoplePickerResolveUser;
var result = JSON.parse(users);
if(users !== undefined){
var reqUrl = appUrl + "/_api/SP.Web.ShareObject";
reqUrl = WebComponents().getTargetUrl(reqUrl, hostUrl);
var shareCall = $.ajax({
url: reqUrl,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify({
"url": reqUrl,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify({
"url": sharedDocUrl,
"peoplePickerInput": '[' + user + ']',
"roleValue": "1073741827",
"groupId": 0,
"propagateAcl": false,
"sendEmail": true,
"includeAnonymousLinkInEmail": true,
"emailSubject": "A document folder has been shared to you",
"emailBody": "A document folder has been shared to you. The folder name is " + folder
})
});
});
shareCall.success(function(data){
myApp.LogInformation("Successfully shared " + folder + " to " + recipient);
});
shareCall.error(function(jqXHR, textStatus){
myApp.LogAPIError(jqXHR, textStatus);
});
}
});}
For generating the Host URL Endpoint
var WebComponents = function(){
var getTargeturl = function (url, hostUrl){
if(hostUrl){
var api = "_api/";
var index = url.indexOf(api);
url = url.slice(0, index + api.length)+
"SP.AppContextSite(#target)" +
url.slice(index + api.length);
var connector = "?";
if(url.indexOf("?") > -1 && url.indexOf("$") > -1){
connector = "&";
}
url = url + connector + "#target='" + hostUrl + "'";
}
return url;
}
return{
getTargeturl: getTargeturl
}}
Can you help verify if I am using the endpoints correctly and if what I am trying to do is even possible?
Appreciate the help.
Cheers,
Neil
Adding my resolution just in case anyone else encounters this issue.
I was able to use the API by:
Removing url = WebComponents().getTargetUrl(url, hostUrl)
and reqUrl = WebComponents().getTargetUrl(reqUrl, hostUrl).
Giving the App Full Control in the Tenant via the AppManifest.xml
I followed this awesome tutorial to get the access and refresh tokens once the user logged in with their google account, but I always this response when I call GetAccessCode():
{
"error": "invalid_request"
}
Here's my code:
var url = window.location.href;
if (url.indexOf("code=") > 0) { //Once the user signed in with Google
var code_starts = url.indexOf("code=");
var code = url.substring((code_starts + 5), url.length);
alert("Code= " + code);
GetAccessTokens(code);
} else if (url.indexOf("access_token=") > 0) { //Get the tokens, but I never get this far
var at_starts = url.indexOf("access_token=");
var exp_starts = url.indexOf("expires_in=");
var access_token = url.substring((at_starts + 13), exp_starts);
alert("AT= " + access_token);
var rt_starts = url.indexOf("refresh_token=");
var id_starts = url.indexOf("id_token=");
var refresh_token = url.substring((rt_starts + 14), id_starts);
alert("RT= " + refresh_token);
} else {
GetAccessCode(); //If user opens the page, show him the consent screen
}
function GetAccessCode() {
window.location = 'https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=https://mywebsite.com/quickstart.html' + '&response_type=code' + '&client_id=' + clientId + '&scope=' + scopes + '&approval_prompt=force' + '&access_type=offline';
}
function GetAccessTokens(code) {
window.location = 'https://accounts.google.com/o/oauth2/token?code=' + code + '&client_id=' + clientId + '&client_secret=' + clientSecret + '&redirect_uri=https://mywebsite.com/quickstart.html' + '&grant_type=authorization_code';
}
Here I receive the invalid_request error.
I tried to get the tokens via an ajax request to not have to redirect the page again (bad UX):
var red = 'https://mywebsite.com/quickstart.html';
var options = {
url: 'https://accounts.google.com/o/oauth2/token',
type: "POST",
dataType: "json",
data: "code=code&client_id=clientId&client_secret=clientSecret&redirect_uri=red&grant_type=authorization_code",
complete: function (e) {
alert(e);
alert(e.status);
},
};
$.ajax(options);
}
I tried it with headers, too:
headers: { "Content-type": "application/x-www-form-urlencoded"},
And I tried it this way, too:
$.ajax({
url: "https://accounts.google.com/o/oauth2/token",
type: "post",
datatype:"json",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
async : true,
data: {code:code, client_id:clientId, client_secret:clientSecret, redirect_uri:'https://mywebsite.com/quickstart.html', grant_type:'authorization_code'},
success: function(response){
alert(response); //I never get this
var json = $.parseJSON(response);
}
})
.fail(function(err) {
alert("error" + err); //I get [Object object]
});
And a few other stuff, too.
Oh, and all the parameters have the correct value.
Any ideas?
Ps: The oauth playground shows that the corrent token url is https://www.googleapis.com/oauth2/v4/token but when I use it I get Not found in the browser.
After 3 days I did it. Thanks for the console.log tip, #Brunt!
$.ajax({
url: 'https://www.googleapis.com/oauth2/v4/token',
type: "post",
datatype:"json",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
async : true,
data: {code:code, client_id:clientId, client_secret:clientSecret, redirect_uri:'https://mywebsite.com/quickstart.html', grant_type:'authorization_code'},
success: function(response){
console.log("Response: " + response);
console.log("AT: " + response['access_token']);
console.log("RT: " + response['refresh_token']);
access_token = response['access_token'];
refresh_token = response['refresh_token'];
}
})
.fail(function(err) {
alert("error" + err); //[Object object]
console.log("error" + err);
});
I have this functions
//send JSON-RPC request
var json_rpc = (function() {
var id = 1;
return function(url, method, params, success) {
if (typeOf(params) != 'array') {
params = [params];
}
var request = JSON.stringify({
'jsonrpc': '2.0',
'method': method,
'params': params,
'id': id++});
return $.ajax({
url: url,
data: request,
success: success,
error: function (XMLHttpRequest, textStatus, errorThrown) {
error_msg('XHR error ' + XMLHttpRequest.status + ' ' +
XMLHttpRequest.responseText);
},
beforeSend: function(xhr) {
console.log('before send');
console.log(dir(xhr));
xhr.onreadystatechange = function(){
console.log('state');
};
},
contentType: 'application/json',
dataType: 'json',
type:"POST"});
}
})();
var rpc = function(method, success_callback) {
//I use functional javascript library
var fun = json_rpc.partial('rpc.php', method, _, function(data) {
if (data['error']) {
var e = 'Json-RPC (' + method + ') ' + data['error']['code'] + ": " +
data['error']['message'];
error_msg(e);
} else {
info_msg("rpc sucess for method '" + method + "'");
success_callback(data['result']);
}
});
return function() {
fun(Array.slice(arguments));
};
};
and when I create function with rpc
var update_news = rpc('get_news', function(data) {
if (data) {
//update news
}
});
and call it
$(document).ready(function() {
...
update_news();
...
});
In Firefox everythig is fine, but in Opera and Chrome the function update_news is not executing, beforeSend is fired but onreadystatechange is not, but when I add
setTimeout(update_news, 0);
Then It's call normaly, also when I create synchronous call by putting async: false in $.ajax call or when I put timeout, timeout: 1. In click handlers it also run as expected.
$('#some_id').click(function() {
update_news();
});
Anybody know why this is happening.