Insert user in PeopleOrGroup Field using javascript SharePoint 2013 - javascript

I have only email address of user.
How to insert user in PeopleOrGroup Field using javascript SharePoint 2013.
If I directly pass email address to filed like
var MyUserEmail = 'mymanger's email adress' \\email id is proper and checked
oListItem.set_item('MyFieldName',MyUserEmail);
Throwing error as invalid data.

The following code for your reference:
<script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var lists = web.get_lists();
var list = lists.getByTitle("CL");
var item = list.getItemById(1);
var assignedToVal = new SP.FieldUserValue();
var MyUserEmail = "app#xx.com";
var userId=GetUserId(MyUserEmail);
assignedToVal.set_lookupId(userId); //specify User Id
item.set_item("MyFieldName",assignedToVal);
item.update();
ctx.executeQueryAsync(
function() {
console.log('Updated');
},
function(sender,args) {
console.log('An error occurred:' + args.get_message());
}
);
});
function GetUserId(emailAddress){
var userId="";
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/siteusers?$select=Id&$filter=Email eq '"+emailAddress+"'";
//execute AJAX request
$.ajax({
url: requestUri,
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
async: false,
success: function (data) {
if(data.d.results.length>0){
userId=data.d.results[0].Id;
}
},
error: function () {
//alert("Failed to get details");
}
});
return userId;
}
</script>

My code which is working. Do the Rest call. you can keep Ajax call as Asynchronous false to get the item before Execution Asynchronous () for item save

Related

JS not autopopulating SharePoint User

I've included a snippet of code that doesn't seem to be doing what I want it to. In the past I've been able to use this to autopopulate a name based on the users name within SharePoint. There's no obvious errors, everything else in the script runs fine, and it appears this does to, it just doesn't do what's intended.
function getWebUserData() {
context = new SP.ClientContext.get_current();
web = context.get_web();
currentUser = web.get_currentUser();
currentUser.retrieve();
context.load(web);
context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod),
Function.createDelegate(this, this.onFailureMethod));
}
function onSuccessMethod(sender, args) {
var userObject = web.get_currentUser();
$("input[Title='Requester']").val(userObject.get_title());
$("input[Title='Requester']").attr('disabled','disabled');
}
Below code works in my local SharePoint 2013. referenced thread
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
function GetCurrentUser() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/currentuser";
var requestHeaders = { "accept": "application/json;odata=verbose" };
$.ajax({
url: requestUri,
contentType: "application/json;odata=verbose",
headers: requestHeaders,
success: onSuccess,
error: onError
});
}
function onSuccess(data, request) {
var userName = data.d.LoginName;
//parse the value.
userName = userName.toString().split("i:0#.w|")[1];
SetUserFieldValue("Requester", userName);
}
function onError(error) {
//alert(error);
}
function SetUserFieldValue(fieldName, userName) {
var _PeoplePicker = $("div[title='" + fieldName + "']");
var _PeoplePickerTopId = _PeoplePicker.attr('id');
var _PeoplePickerEditer = $("input[title='" + fieldName + "']");
_PeoplePickerEditer.val(userName);
var _PeoplePickerOject = SPClientPeoplePicker.SPClientPeoplePickerDict[_PeoplePickerTopId];
_PeoplePickerOject.AddUnresolvedUserFromEditor(true);
}
GetCurrentUser();
});
</script>

Using AJAX to post data into API

I have a script that uses AJAX to comunicate with PHP based API.
First part loads trade history:
$(document).ready(function () {
var orders = $('#History ul');
var user = "<?php echo $user; ?>";
$.ajax({
type: "GET",
url: "api.php",
data: {
user: user
},
success: function (response) {
console.log(response);
var res = JSON.parse(response);
$.each(res, function (index, value) {
console.log(value);
if(value['PL']>=0){
orders.append("<li style=\"color:green;\">" + value['User'] + "</li>");
}else{orders.append("<li style=\"color:red;\">" + value['User'] + "</li>");}
});
}
});
Second part posts a trade to database:
$("#submit").click(function(){
//event.preventDefault();
var oPrice = newOrder.elements["oPrice"].value;
var cPrice = newOrder.elements["cPrice"].value;
var oType = newOrder.elements["oType"].value;;
var oSymbol = newOrder.elements["oSymbol"].value;
var oAmount = newOrder.elements["oAmount"].value;
var json ={
'user': user,
'oPrice': oPrice,
'cPrice': cPrice,
'oType': oType,
'oSymbol': oSymbol,
'oAmount': oAmount};
alert(JSON.stringify(json)); //---check zda je naplněný
$.ajax({
type: "POST",
url: "api.php",
data: json,
success: function (response) {
alert(response);
}
});
});
The problem is, that when i press the button and send json, its missing the 'user' data and looks like this:
TraderBook.php?oPrice=1&cPrice=1&oType=LONG&oSymbol=1&oAmount=1
I have no idea why does ajax exclude it. The json variable has it filled out
I think your problem might be here
$(document).ready(function () {
var user = "<?php echo $user; ?>";
var is the JS scoping declaration. So you're limiting your user value to just the anonymous function being triggered by the page DOM load completing. What you should do is try scoping it outside the function
var user; //global scope
$(document).ready(function () {
user = "<?php echo $user; ?>";
This way, when your $("#submit").click(function() fires, there's a value to feed into your script.
I was wrongchecking the problem a mistook data from a form for the json. Problem was inside the API --> There was a tabulator in a SQL command..
Thanks to everyone for suggestions.

SharePoint 2013 get current user using JavaScript

How to get current user name using JavaScript in Script Editor web part?
Here is the code that worked for me:
<script src="/SiteAssets/jquery.SPServices-2013.02a.js" type="text/javascript"></script>
<script src="/SiteAssets/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
var userid= _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : onSuccess,
error : onError
});
function onSuccess(data, request){
var loginName = data.d.Title;
alert(loginName);
}
function onError(error) {
alert("error");
}
</script>
I found a much easier way, it doesn't even use SP.UserProfiles.js. I don't know if it applies to each one's particular case, but definitely worth sharing.
//assume we have a client context called context.
var web = context.get_web();
var user = web.get_currentUser(); //must load this to access info.
context.load(user);
context.executeQueryAsync(function(){
alert("User is: " + user.get_title()); //there is also id, email, so this is pretty useful.
}, function(){alert(":(");});
Anyways, thanks to your answers, I got to mingle a bit with UserProfiles, even though it is not really necessary for my case.
If you are in a SharePoint Page just use:
_spPageContextInfo.userId;
How about this:
$.getJSON(_spPageContextInfo.webServerRelativeUrl + "/_api/web/currentuser")
.done(function(data){
console.log(data.Title);
})
.fail(function() { console.log("Failed")});
You can use the SharePoint JSOM to get your current user's account information. This code (when added as the snippet in the Script Editor web part) will just pop up the user's display and account name in the browser - you'll want to add whatever else in gotAccount to get the name in the format you want.
<script type="text/javascript" src="/_layouts/15/SP.js"></script>
<script type="text/javascript" src="/_layouts/15/SP.UserProfiles.js"></script>
<script type="text/javascript">
var personProperties;
SP.SOD.executeOrDelayUntilScriptLoaded(getCurrentUser, 'SP.UserProfiles.js');
function getCurrentUser() {
var clientContext = new SP.ClientContext.get_current();
personProperties = new SP.UserProfiles.PeopleManager(clientContext).getMyProperties();
clientContext.load(personProperties);
clientContext.executeQueryAsync(gotAccount, requestFailed);
}
function gotAccount(sender, args) {
alert("Display Name: "+ personProperties.get_displayName() +
", Account Name: " + personProperties.get_accountName());
}
function requestFailed(sender, args) {
alert('Cannot get user account information: ' + args.get_message());
}
</script>
See the SP.UserProfiles.PersonProperties documentation in MSDN for more info.
To get current user info:
jQuery.ajax({
url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/currentuser",
type: "GET",
headers: { "Accept": "application/json;odata=verbose" }
}).done(function( data ){
console.log( data );
console.log( data.d.Title );
}).fail(function(){
console.log( failed );
});
U can use javascript to achive that like this:
function loadConstants() {
this.clientContext = new SP.ClientContext.get_current();
this.clientContext = new SP.ClientContext.get_current();
this.oWeb = clientContext.get_web();
currentUser = this.oWeb.get_currentUser();
this.clientContext.load(currentUser);
completefunc:this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));
}
//U must set a timeout to recivie the exactly user u want:
function onQuerySucceeded(sender, args) {
window.setTimeout("ttt();",1000);
}
function onQueryFailed(sender, args) {
console.log(args.get_message());
}
//By using a proper timeout, u can get current user :
function ttt(){
var clientContext = new SP.ClientContext.get_current();
var groupCollection = clientContext.get_web().get_siteGroups();
visitorsGroup = groupCollection.getByName('OLAP Portal Members');
t=this.currentUser .get_loginName().toLowerCase();
console.log ('this.currentUser .get_loginName() : '+ t);
}
I had to do it using XML, put the following in a Content Editor Web Part by adding a Content Editor Web Part, Edit the Web Part, then click the Edit Source button and paste in this:
<input type="button" onclick="GetUserInfo()" value="Show Domain, Username and Email"/>
<script type="text/javascript">
function GetUserInfo() {
$.ajax({
type: "GET",
url: "https://<ENTER YOUR DOMAIN HERE>/_api/web/currentuser",
dataType: "xml",
error: function (e) {
alert("An error occurred while processing XML file" + e.toString());
console.log("XML reading Failed: ", e);
},
success: function (response) {
var content = $(response).find("content");
var spsEmail = content.find("d\\:Email").text();
var rawLoginName = content.find("d\\:LoginName").text();
var spsDomainUser = rawLoginName.slice(rawLoginName.indexOf('|') + 1);
var indexOfSlash = spsDomainUser.indexOf('\\') + 1;
var spsDomain = spsDomainUser.slice(0, indexOfSlash - 1);
var spsUser = spsDomainUser.slice(indexOfSlash);
alert("Domain: " + spsDomain + " User: " + spsUser + " Email: " + spsEmail);
}
});
}
</script>
Check the following link to see if your data is XML or JSON:
https://<Your_Sharepoint_Domain>/_api/web/currentuser
In the accepted answer Kate uses this method:
var userid= _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")
you can use below function if you know the id of the user:
function getUser(id){
var returnValue;
jQuery.ajax({
url: "http://YourSite/_api/Web/GetUserById(" + id + ")",
type: "GET",
headers: { "Accept": "application/json;odata=verbose" },
success: function(data) {
var dataResults = data.d;
alert(dataResults.Title);
}
});
}
or you can try
var listURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/currentuser";
try this code..
function GetCurrentUsers() {
var context = new SP.ClientContext.get_current();
this.website = context.get_web();
var currentUser = website.get_currentUser();
context.load(currentUser);
context.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));
function onQuerySucceeded() {
var currentUsers = currentUser.get_title();
document.getElementById("txtIssued").innerHTML = currentUsers;
}
function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
}
You can use sp page context info:
_spPageContextOnfo.userLoginName

Set the function itself to the url in AJAX?

I am new to AJAX. Recently, I read a block of code that set url to the function itself. In this case, it is get Path. Normally, we will set url to other pages to get data or something. I do not know what it means to set url to the calling function itself. Could you help answer my question?
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
$.ajax({
type: "POST",
url: "getPath",
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>
function getPath() <-- function
url: "getPath", <-- string
They are not related. Only thing in common is the developer had the same name. The page will post to some location called getPath on the server.
It doesn't mean anything other than the fact that the url the POST request is being sent to happens to be "getPath". The function is probably named according to the route name on the server side, but renaming that function (and updating every place it is called accordingly) would have no effect, and you would have to leave the url: "getPath" as is. Changing that part would likely break something.
That getPath would be a relative url, so the request goes to something like: http://example.com/path/to/parent/of/current/page/getPath
suppose your HTML input URL
<input type="url" id="web_url" value=""></input>
Then you can get your URL
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
var url = $('#web_url').val(); // getting input URL by User
$.ajax({
type: "POST",
url:url ,
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>

I don't understand AJAX callbacks

I have a javascript function which executes on the change of a dropdown:
<script type="text/javascript">
$(function()
{
// Executes when the status dropdown changes value
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
})
</script>
I am trying to get the alert call to show the return value of the following php code (which is true):
<?php
.
.
.
return true;
?>
The alert doesn't pop up. Anyone know why ???
I tried your code with another URL and it's working well.
There are three cases:
scriptUrl is not calculated properly and doesn't point to your PHP script
your server is down
you are accessing an URL not served under the same domain as the one of your script (same-origin policy)
You can see detail of your error if you add an error handler to ajax parameters :
error : function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
Return only returns a value within the php script - to output it to ajax you need to actually output the result to the page, in this case something like echo "true"; or print("true");
Try this
$(document).ready(function(){
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
});

Categories

Resources