JS not autopopulating SharePoint User - javascript

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>

Related

Insert user in PeopleOrGroup Field using javascript SharePoint 2013

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

Open a view in new tab from javascript when controller returns

I need to open a new tab after the controller success, the controller returns a View
This is my approach but it doesn't work:
function modify(){
var1= someDataFromDOM;
var2= anotherDataFromDOM;
$.ajax({
method: 'POST',
url: '#Url.Action("ModifyObject", "ControllerName")',
data: {id: var1, status: var2},
success: function (data){
var newTab = window.open("", "_blank", "", true);
newTab.document.body.innerHTML = data;
}
});
}
On the controller
[HttpPost]
public ActionResult ModifyObject(int id, string status)
{
ViewModelA model = new ViewModelA();
model = bd.GetModelA(id, status);
return View("ModifyObject", model);
}
The controller returns the view correctly but the newTab variable has null value
Any help will be welcome
I think the problem is with the javascript window.open(). This function is blocked by browsers except user events. See here and here
Below is a workaround for your purposes, I have tested;
<input type="button" hidden="hidden" id="hack" />
$(function () {
var var2 = "test";
var var1 = 1;
var htmlData;
var win;
$.ajax({
method: 'POST',
url: '#Url.Action("ModifyObject", "Controller")',
data: { id: var1, status: var2 },
success: function (data) {
htmlData = data;
$("#hack").trigger("click");
}
});
$("#hack").on("click", function () {
win = window.open("", "_blank");
win.document.body.innerHTML = htmlData;
});
});
However, opening a new tab like this may not be a good approach.
It is not apperant what your modify() does, but I would not use ajax to open a new window, I would try to replace it with the below instead, please check here
Html.ActionLink("LinkText", "ModifyObject", "ControllerName", new { Id = "param1", Status = "param2" }, new { target = "_blank" });
Update
Try this as per your comment;
function modify()
{
var grid = $("#datagrid").data("kendoGrid");
var row = grid.getSelectedRow();
var win = window.open("","_blank")
var var1 = row.fieldID;
var var2 = row.fieldStatus;
var url = '#Url.Action("ModifyObject", "ControllerName")' + '?id=' + var1 + '&status=' + var2;
win.location = url;
}

How to Call a Web Service in a Cross-Browser way

I want to call a Web Service from Mozilla, Internet Explorer and Chrome.
Bellow is my LaboratoryService.js file which calls the Web Service:
function StringBuffer() {
this.__strings__ = new Array;
}
StringBuffer.prototype.append = function (str) {
this.__strings__.push(str);
};
StringBuffer.prototype.toString = function () {
return this.__strings__.join("");
};
function LaboratoryService() {
this.url = "http://25.48.190.93:8082/labratory?wsdl";
}
LaboratoryService.prototype.buildRequest = function () {
var oBuffer = new StringBuffer();
oBuffer.append("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" ");
oBuffer.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
oBuffer.append("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">");
oBuffer.append("<soap:Body>");
oBuffer.append("<getLabratory xmlns=\"http://nano.ito.ir/\" />");
oBuffer.append("</soap:Body>");
oBuffer.append("</soap:Envelope>");
return oBuffer.toString();
};
LaboratoryService.prototype.send = function () {
var oRequest = new XMLHttpRequest;
oRequest.open("post", this.url, false);
oRequest.setRequestHeader("Content-Type", "text/xml");
oRequest.setRequestHeader("SOAPAction", this.action);
oRequest.send(this.buildRequest());
if (oRequest.status == 200) {
return this.handleResponse(oRequest.responseText);
} else {
throw new Error("Request did not complete, code " + oRequest.status);
}
};
LaboratoryService.prototype.handleResponse = function (sResponse) {
var start = sResponse.indexOf('div') - 4;
var end = sResponse.lastIndexOf('div') + 7;
return sResponse.substring(start, end);
};
Bellow is my HTML code which uses LaboratoryService.js to show data:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get Labratories</title>
<script language="JavaScript" src="LaboratoryService.js"></script>
<script language="JavaScript" src="jquery-1.8.0.min.js"></script>
<script language="JavaScript" type="text/javascript">
$(document).ready(function () {
$("#btnGetLaboratories").click(function () {
var oService = new LaboratoryService();
var fResult = oService.send();
var newData = $('<div/>').html(fResult).text();
$("#divResult").html(newData);
});
});
</script>
</head>
<body>
<input id="btnGetLaboratories" type="button" value="Get Laboratories" />
<div id="divResult">
</div>
</body>
</html>
This approach works fine in Internet Explorer.
The problem is that this approach does not work in FireFox and Chrome.
I think that the oRequest.send(this.buildRequest()); does not work in FireFox and Chrome.
Edited Web Service Call Using JQuery
I changed LaboratoryService.prototype.send to use JQuery to call Web Service as bellow:
LaboratoryService.prototype.send = function () {
$.ajax({
type: "POST",
url: this.URL,
contentType: "text/xml",
headers: { "SOAPAction": this.action },
success: function (msg) {
return this.handleResponse(msg);
},
error: function (e) {
alert('error');
}
});
};
But it alerts error. How do I call Web Service using JQuery?
Again Edited Code
I changed my JQuery AJAX call as bellow. It works fine in Internet Explorer but returns error in Chrome and Firefox.
LaboratoryService.prototype.send = function () {
$.ajax({
type: "POST",
url: this.URL,
contentType: "text/xml; charset=\"utf-8\"",
dataType: "xml",
data: this.buildRequest(),
processData: false,
success: function processSuccess(data, status, req) {
if (status == "success") {
var sResponse = req.responseText;
var start = sResponse.indexOf('div') - 4;
var end = sResponse.lastIndexOf('div') + 7;
var newData = $('<div/>').html(sResponse.substring(start, end)).text();
$("#divResult").html(newData);
}
},
error: function () {
alert('error');
}
});
};
Just change :
LaboratoryService.prototype.send = function () {
var oRequest = new XMLHttpRequest;
oRequest.open("post", this.url, true);
oRequest.setRequestHeader('User-Agent','XMLHTTP/1.0');
oRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oRequest.setRequestHeader("SOAPAction", this.action);
oRequest.send(this.buildRequest());
if (oRequest.status == 200) {
return this.handleResponse(oRequest.responseText);
} else {
throw new Error("Request did not complete, code " + oRequest.status);
}
};
Please, refer this link.

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

when fast cliking on like button getting unknown likes

i am working on project which have like unlike function look like facebook but i am getting stuck when i click multiple time at once on like button or unlike button then its work like firing and if i have 1 or 2 like and i click many time fast fast then my likes gone in -2 -1. how i solve this issue ? if when click many time always get perfect result. below my jquery script
$(document).ready(function () {
$(".like").click(function () {
var ID = $(this).attr("idl");
var REL = $(this).attr("rel");
var owner = $(this).attr("owner");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL + '&owner=' + owner;
$.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false,
success: function (html) {
if (REL == 'Like') {
$('.blc' + ID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
$('.spn' + ID).html(html);
} else {
$('.blc' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
$('.spn' + ID).html(html);
}
}
});
});
});
It is because of the async nature of ajax request.... when you click on the element continuously... the click event will get fired before the response from previous request come back and the link status is updated to next one
Case:
Assume the rel is unlike, then before the response came back again another click happens so the rel is not yet updated so you are sending another unlike request to server instead of a like request
Try below solution(Not Tested)
$(document).ready(function () {
var xhr;
$(".like").click(function () {
var ID = $(this).attr("idl");
var REL = $(this).attr("rel");
var owner = $(this).attr("owner");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL + '&owner=' + owner;
if (REL == 'Like') {
$('.blc' + ID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
} else {
$('.blc' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
}
//abort the previous request since we don't know the response order
if (xhr) {
xhr.abort();
}
xhr = $.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false
}).done(function (html) {
$('.spn' + ID).html(html);
}).always(function () {
xhr = undefined;
});
});
});
Set a variable, we'll call it stop and toggle it.
$(document).ready(function () {
var stop = false;
$(".like").click(function () {
if (!stop)
{
stop = true;
var ID = $(this).attr("idl");
var REL = $(this).attr("rel");
var owner = $(this).attr("owner");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL + '&owner=' + owner;
$.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false,
success: function (html) {
if (REL == 'Like') {
$('.blc' + ID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
$('.spn' + ID).html(html);
} else {
$('.blc' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
$('.spn' + ID).html(html);
}
}
}).always(function() { stop = false; });
}
});
});

Categories

Resources