Error creating communication site in Sharepoint Online via REST and Javascript - javascript

I'm trying to create a sharepoint online site collection based on the Communication site template, as described by Microsoft here https://learn.microsoft.com/en-us/sharepoint/dev/apis/communication-site-creation-rest by using javascript on a page in a different sharepoint site
But, I keep getting a response of 403- although I am a tenant admin and so definitely have permission to create sites.
I am running the script below from a page at a url like companyname.sharepoint.com/sites/myTestSite/sitepages/RunSomeJS.aspx
I have tried specifying REST endpoint domain of both
companyname.sharepoint.com
and
companyname-admin.sharepoint.com
but get the same error.
function DoRestCall(){
var body={'parameters':
{
"__metadata":{"type":"SP.Publishing.CommunicationSiteCreationRequest"},
"AllowFileSharingForGuestUsers":false,
"Classification":"MyTest Communication Site",
"Description":"Here is my communication site",
"SiteDesignId":"6142d2a0-63a5-4ba0-aede-d9fefca2c767",
"Title":"MyTest Communication Site",
"Url":"https://companyname.sharepoint.com/sites/testSiteName",
"lcid":1033
}
};
$.ajax({
type: 'POST',
url: "https://companyname.sharepoint.com/_api/sitepages/create",
contentType: 'application/json',
processData: false,
headers:{
"accept":"application/json;odata=verbose",
"content-type":"application/json;odata=verbose",
"X-RequestDigest": document.getElementById("__REQUESTDIGEST").value
},
data: JSON.stringify(body),
success: function ()
{
alert('CREATION REQUEST SUBMITTED');
},
error: function(data){
alert('failure:' + data.statusText );
}
});
}
Any suggestions as to what I'm doing wrong here?

You need to make couple of changes as below:
1) Change the metadata as below:
"__metadata":{"type":"SP.Publishing.PublishingSiteCreationRequest"},
2) You need to replace parameters to request
3) Modify the endpoint to create communication site as below:
url: "https://companyname.sharepoint.com/_api/sitepages/publishingsite/create",
3) Ensure that you are running the code from the root site(whose url is like https://companyname.sharepoint.com/sitepages/RunSomeJS.aspx) and you are the site collection admin of that root site.
You final code would be as below:
function DoRestCall(){
var body={'request':
{
"__metadata":{"type":"SP.Publishing.PublishingSiteCreationRequest"},
"AllowFileSharingForGuestUsers":false,
"Classification":"MyTest Communication Site",
"Description":"Here is my communication site",
"SiteDesignId":"6142d2a0-63a5-4ba0-aede-d9fefca2c767",
"Title":"MyTest Communication Site",
"Url":"https://companyname.sharepoint.com/sites/testSiteName",
"lcid":1033
}
};
$.ajax({
type: 'POST',
url: "https://companyname.sharepoint.com/_api/sitepages/publishingsite/create",
contentType: 'application/json',
processData: false,
headers:{
"accept":"application/json;odata=verbose",
"content-type":"application/json;odata=verbose",
"X-RequestDigest": document.getElementById("__REQUESTDIGEST").value
},
data: JSON.stringify(body),
success: function ()
{
alert('CREATION REQUEST SUBMITTED');
},
error: function(data){
alert('failure:' + data.statusText );
}
});
}

Related

Django API call from extern Website via AJAX Javascript

i am working for the first time with Django Framework. A service provider is using django i can see the data only with an active Cookie on their API Docs.
We received now an API Token to call for the data on the framework.
I am trying to call the data with the Token via AJAX but i receive everytime the same console log "401 (Unauthorized)".
$.ajax({
type: 'POST',
headers: {
'X-CSRFTOKEN': "XXXXXXXXXXXXXXX",
'Content-Type': 'application/json'
},
url: 'www.service-provider.url/api/...',
success: function () {
console.log("ok");
},
error: function () {
console.log("error");
}
});
Sorry i'm a beginner at this point and have no idea where to begin with. I've searched for solution on the inet but couldn't find anything that would work.
Okay i got it! Before the token api key there must be "Token ...".
$.ajax({
type: 'GET',
url: 'https://my-url.com/api/1.0/?format=json',
headers:{
"Content-Type": 'application/json',
"Authorization": 'Token XXXXXXXXXXXXXXXXXXXXX',
},
success: function(data){
console.log(data);
}
});

How to update outlook 2.0 API token using refresh-token?

I have next situation:
Main authentication flow happens on server, then client side obtains these data, since that moment I wanna client be able to update token by itself. It's seems there is all needed data on client(access_token, refresh_token), but I can't figure out how to organize request to https://login.microsoftonline.com/common/oauth2/v2.0/token route.
First I tried to get json response:
$.ajax({
url: `https://login.microsoftonline.com/common/oauth2/token?grant_type=refresh_token&refresh_token=refresh_token&scope=openid%20profile%20offline%20access%20user.read%20mail.read%20contacts.read%20calendars.read&client_id=client&client_secret=secret`,
type: 'POST',
cache: false,
processData: false,
contentType: false,
dataType: 'json',
headers: {
'Host': 'https://login.microsoftonline.com',
'Content-Type': 'application/json'
},
success: function(data) {
...
},
error: function(xhr) {
...
}
});
After that I figured out that it's only possible to get this data with redirect, is it correct? If it is, can someone produce an example of how to implement this, looks like it's needed to create an iframe and handle authorization somehow. Thanks.
UPDATED:
as Alina Li pointed in comment to her answer, there is a solution right in the official doc https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
According to my test, you could using refresh-token through the below code:
var data = "grant_type=refresh_token&refresh_token=refreshToken&client_id=" + appState.clientId;
$http = $http || $injector.get('$http');
$http.post(authUrl + '/token', data, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (response) {
}).error(function (err, status) {
});
You don’t need to add scope parameter.
Reference from:
Storing Refresh Token In JavaScript, Getting New Access Token

Github API v3: Update file not working (404)

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!');
});

Uncaught SyntaxError: Unexpected token u with Ajax post

I am stumped as to how to solve/diagnose ajax/jquery error.
This is my function:
var LogIn = {
Email: $("#Name").val(),
MobileNo: $("#txtMobileNumber").val(),
PinCode: '',
Message: '',
Success:false
};
$.ajax({
type: "POST",
crossDomain: true,
dataType: 'jsonp',
contentType: "application/json",
url: "https://a different server domain/api/LoginRequest",
data: JSON.stringify(LogIn),
success: function (data) {
$("#divError").html(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
$("#divError").html(jsonValue);
}
});
I get this error:
jQuery doesn't support using POST and jsonp and the reason for that is very simple: when you inject a <script> tag into the DOM (which is what jQuery does when you use jsonp), the browser will send a GET request to the remote endpoint which has been referred to in the src property of this tag.
So basically you will need to use GET instead:
type: "GET"
Also since the data is sent as query string parameters you should remove the content type:
contentType: "application/json",
and do not JSON.stringify the data.
And here's the full example:
$.ajax({
type: "GET",
crossDomain: true,
dataType: 'jsonp',
url: "https://a different server domain/api/LoginRequest",
data: LogIn,
success: function (data) {
$("#divError").html(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
$("#divError").html(jsonValue);
}
});
Of course this will work only if the remote endpoint supports JSONP and the GET verb.
Personally I would recommend using CORS instead of JSONP as it would give you much more options. You will be able to use POST in this case. Please refer to the following material as it seems you are using ASP.NET Web API on the server and trying to make a cross domain AJAX call: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

"400 Bad Request" response for AJAX request

I have the following jQuery AJAX request:
// collect form data and create user obj
var user = new User();
user.firstname = $("#usrFirstName").val();
user.lastname = $("#usrSurname").val();
user.role = $("#usrRole").val();
// actual ajax request
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: user,
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(data, status) {
alert(JSON.stringify(data));
}).fail(function(data, status) {
alert(status);
alert(JSON.stringify(data));
});
The response from the Server is:
"status":400,"statusText":"Bad Request"
"The request sent by the client was syntactically incorrect."
The server is running Spring-MVC. But as far as I can tell it is working correctly. Because if I'm sending a request manually with Postman and the following configuration it works.
Header:
Content-Type application/json; charset=utf-8
Content:
{"firstname":"alex","lastname":"lala","role":"admin"}
I have to mention that it is a cross-domain request (for the time developing, it will be hosted on the same domain as the server later). I did disable the security settings in the browser and AJAX requests to the server are working fine (as long as I don't have to send data).
you need to serialize your json, try:
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user),
contentType:'application/json; charset=utf-8',
dataType: 'json'
})
JSON.stringify() method is used to turn a javascript object into json string. You need to have this. In addition it is better to include success and error portions in the AJAX.
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user), // turn a javascript object into json string
contentType:'application/json; charset=utf-8',
dataType: 'json',
success: function (html) {
alert(html);
}, error: function (error) {
alert(error);
}
})

Categories