I am trying to create a SP 2013 site through the REST API via Jquery AJAX. I have extracted the REQUEST_DIGEST from the '/_api/contextinfo' call. Next, while trying to set the X-RequestDigest header for the '/_api/web/webinfos/add' call ,a pre-flight request with method 'OPTIONS' is sent by the browser which is getting a HTTP 403 response code. As per my understanding , it is expecting the FedAuth cookie , while the browser, according to the CORS principle is not sending the authentication info. It seems that the 'OPTIONS' verb need to be configured on the SP 2013 and I have not found any clear solution for this. Is my understanding correct , in which case can anyone provide a solution ?
I created this code that works on my Sharepoint 2013 environment.
First, I try my ajax request with a relative URL like this : /_api/web/webinfos/add
The resquest result in a 403 Forbidden.
Then I retry with : _spPageContextInfo.webAbsoluteUrl + "/_api/web/webinfos/add"
and this time it works fine.
The reason is that my site collection URL pattern is :
http://domain/manage-path/site-collection
So when I use a relative URL /_api/web/webinfos/add its the same as using :
http://domain/_api/web/webinfos/add
Because its not the address of the current site collection Sharepoint returns a Cross-Site Scripting error.
But When I use _spPageContextInfo.webAbsoluteUrl + "/_api/web/webinfos/add" it give me the full URL of the site collection :
http://domain/manage-path/site-collection/_api/web/webinfos/add
Here is the complete script :
<script language="JavaScript" type="text/javascript">
function createSubsiteUsingREST(data,siteTitle,siteUrl,siteDescription) {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/webinfos/add",
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
data: JSON.stringify({
'parameters': {
'__metadata': {
'type': 'SP.WebInfoCreationInformation'
},
'Url': siteUrl,
'Title': siteTitle,
'Description': siteDescription,
'Language': 1033,
'WebTemplate': 'sts',
'UseUniquePermissions': true
}
}),
success:function(){
alert('SubSite Created with success!');
},
error:function(){
alert('oups! An error occured during the process of creating this new SubSite!');
}
});
}
$(document).ready(function() {
$('#btnCreateSubSiteWithREST').on('click',function() {
var siteTitle = $('#txtSiteTitle').val();
var siteUrl = $('#txtSiteUrl').val();
var siteDescription = $('#txtSiteDescription').val();
createSubsiteUsingREST(siteTitle,siteUrl,siteDescription);
});
});
</script>
<input type="button" id="btnCreateSubSiteWithREST" value="Create New SubSite Using REST">
<div><label>Title of the SubSite : </label><input type="text" id="txtSiteTitle"></div>
<div><label>URL of the SubSite : </label><input type="text" id="txtSiteUrl"></div>
<div><label>Description of the SubSite : </label><input type="text" id="txtSiteDescription"></div>
Hope this help!
Related
I want to render a template after a Ajax call.
My code is:
index.pug
include form.pug
+list('style')
form.pug
mixin list(style)
p(class=style) my form
I want to add form.pug after click a button, so
my ajax call is:
$.ajax({
url: "/myroute",
method: "POST",
data: msgObj,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
datatype: "json",
success: function (msg) {
div.prepend(msg.template)
},
});
/myroute (server-node) is:
const pug = require('pug');
var template = pug.renderFile('Path/form.pug');
res.send({"template":template,"style":"new_style"});
My template doesn't appear after click the button.
In I remove mixin, everything works, but I need pass a param during the template generation
Call the mixin somewhere in the page, select it in the DOM after AJAX call and fill the needed values before prepending it.
I have been trying to load a multiple file HTML input using Ajax and Django, I know that there are a bunch of questions related to this problem here in StackOverflow but none of the methods have worked for me. I am trying to use a single web page. I would appreciate any recommendation:
HTML Code: This code is inserted also with a click function using ajax, that is why there are a lot of + symbols and everything is inside quotation marks
+'<form id="reclamo" action="{% url "denuncia" %}" method="post" enctype="multiport/form-data">'
+'{% csrf_token %}'+'<label for="files">Adjuntos:</label>'+'<b> </b>'
+'<input type="file" id="files" name="files" multiple><br><br>'
+'<input type="submit" name="upload" value="Reportar">'
+"</form>"
And this one is the Ajax code:
$(document).on('submit','#reclamo',function(e) {
e.preventDefault();
var frm = new FormData($('#reclamo').get(0));
$.ajax({
url: "/denuncia/",
type: "POST",
data: frm,
cache:false,
proccessData: false,
contentType: false,
headers:{
'X-CSRFToken':'{{csrf_token}}'
},
success: function(result){
if (result == 'saved') {
alert('ha sido creada con exito')
}
}
});
})
The error I am getting is:
Uncaught TypeError: Illegal invocation
at e (jquery-3.1.1.min.js:4)
at xb (jquery-3.1.1.min.js:4)
at Function.r.param (jquery-3.1.1.min.js:4)
at Function.ajax (jquery-3.1.1.min.js:4)
at HTMLFormElement.<anonymous> ((index):226)
at HTMLDocument.dispatch (jquery-3.1.1.min.js:3)
at HTMLDocument.q.handle (jquery-3.1.1.min.js:3)
Looks like your data attribute is misspelled. Not sure if this solves it, just saw it. Try edit it to formData.
I have recently created a sharepoint list that has a multitude of radio button choices. When the user creates a new entry, they pick a radio button and submit. However, when they view using the display form, only the choice that they selected appears. I want to make it so that ALL of the possible choices appear, but it still shows what they have picked. Is there any possible way of doing this?
This is what appears currently
This is what I want (and what users see when they submit a new item)
We can use REST API to get all the filed choices and then append the HTML to the field in the display form using jQuery. The following code for your reference. Add the code into a script editor web part in the dispform.aspx page.
<script src="//code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var fieldTitle="AP Coding/Slip Claim Forms*/Limited Purchase Order";
var currentFieldValue=$("h3.ms-standardheader:contains('"+fieldTitle+"')").parent().next()[0].innerText.trim();
var fieldHTML=GetFieldChoices(currentFieldValue,fieldTitle);
$("h3.ms-standardheader:contains('"+fieldTitle+"')").parent().next().html(fieldHTML);
});
function GetFieldChoices(currentFieldValue,fieldTitle){
var listId = _spPageContextInfo.pageListId.replace("{","").replace("}","");
var fieldHTML="";
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists(guid'"+listId+"')/fields?$select=Choices&$filter= Title eq '"+fieldTitle+"'";
$.ajax({
url: url,
method: "GET",
async:false,
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var choices = data.d.results[0].Choices.results;
$.each(choices,function(index,choice){
if(choice==currentFieldValue){
fieldHTML+="<input type='radio' disabled='disabled' checked='checked' name='"+fieldTitle+"' value='"+choice+"'>"+choice;
}else{
fieldHTML+="<input type='radio' disabled='disabled' name='"+fieldTitle+"' value='"+choice+"'>"+choice;
}
if(index<choices.length){
fieldHTML+="<br>";
}
});
},
error: function (error) {
console.log(JSON.stringify(error));
}
});
return fieldHTML;
}
</script>
When getting the URL from the current user's profile via REST, the image tag is not able to display when the src is updated:
<img id="escMyPic" src="" alt="" />
<script type="text/javascript">
$.ajax({
url: strURL + "/_api/sp.userprofiles.peoplemanager/getmyproperties",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: MyPictureSucceeded,
error: MyPictureFailed
});
function MyPictureSucceeded(data) {
if(data.d.PictureUrl != null) {
$('#escMyPic').attr('src', data.d.PictureUrl);
}
}
function MyPictureFailed() {
alert('Error: Unexpected error loading profile picture.');
}
</script>
The return url looks like this in SharePoint Online:
https://tenant-my.sharepoint.com:443/User%20Photos/Profile%20Pictures/email_address_MThumb.jpg?t=63601764394
It redirects to:
https://tenant-my.sharepoint.com/User%20Photos/Profile%20Pictures/email_address_MThumb.jpg?t=63601764394
Using browser dev tools, you see the mime type that comes back is not image/jpg but text/plain. I've removed the query string parameter, and even placed the hard coded URL in the image tag src, but it just doesn't display. Also the response body in the dev tools is blank. It appears to be redirecting and authenticating before showing.
When placing the hard coded URL in the browser address bar, the picture shows fine, and the dev tools response header shows the picture as the contents of the URL, and the MIME type is image/jpg.
How do you get the profile image to show from a REST call?
In addition to /_api/sp.userprofiles.peoplemanager/getmyproperties endpoint which returns PersonalUrl property, user profile picture could be requested via _layouts/15/userphoto.aspx?size=<size>&accountname=<accountname> page, where
size - could be set to S/M/L which stands for Small/Medium/Large
image size
accountname - user account name
Example
var url = getMyPictureUrl(_spPageContextInfo.webAbsoluteUrl,_spPageContextInfo.userLoginName,"M");
$('#escMyPic').attr('src', url);
where
function getMyPictureUrl(webUrl,accountName,size){
return webUrl + "/_layouts/15/userphoto.aspx?size=" + size + "&accountname=" + accountName;
}
Is it possible to create a form visual webpart with fields like name, email, address and submit button. After user submit data should be submitted to sharepoint custom list here custom list will have same fields like name, email, address. I created one custom list.
I search on internet but i didn't find any solutions for that. Also am new to sharepoint. If any one can provide some links it will be helpful.
Thanks
Yes, this is very possible using jQuery and AJAX.
So, lets say that, just to be brief, this is your input:
<input type='text' id='name' />
<input type='submit' id='submitdata' value='submit />
Using jquery, you would do this:
$(function(){
$('#submitdata').click(function(){
//this gets the value from your name input
var name = $('#name').val();
var list = "PutYourListNameHere";
addListItem(name, list);
});
});
function addListItem(name, listname) {
var listType = "PutTheTypeOfListHere";
// Prepping our update & building the data object.
// Template: "nameOfField" : "dataToPutInField"
var item = {
"__metadata": { "type": listType},
"name": name
}
// Executing our add
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
console.log("Success!");
console.log(data); // Returns the newly created list item information
},
error: function (data) {
console.log("Error!");
console.log(data);
}
});
}
This SHOULD work. I am not at work where my SharePoint station is, so if you are still having issues with this, let me know.
You may use SPServices also, It will work
<script type="text/javascript" src="~/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="~/jquery.SPServices-0.7.2.min.js"></script>
HTML
<input type='text' id='name' />
<input type='text' id='email' />
<input type='text' id='mobile' />
<input type='submit' id='submit' value='Submit' />
SPServices
<script type="text/javascript">
$("#submit").click(function(){
var Fname=$("#name").val();
var Email =$("#email").val();
var Mobile =$("#mobile").val();
$().SPServices({
operation: "UpdateListItems",
async: false,
batchCmd: "New",
listName: "YourCustomListName",
valuepairs: [["Fname", Fname], ["Email", Email], ["Mobile", Mobile]], //"Fname","EMail" and "Mobile" are Fields Name of your custom list
completefunc: function(xData, status) {
if (status == "success") {
alert ("Thank you for your inquiry!" );
}
else {
alert ("Unable to submit your request at this time.");
}
}
});
});
</script>