Get current logged in user from SharePoint and filter DataTable with it
Get current logged in user from SharePoint and filter DataTable with it
Katia_LT
Posts: 13Questions: 6Answers: 0
I draw DataTable in successFunction using data from ajax call:
function loadListItems() {
var oDataUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('orders')/items?$select=ID,Title";
$.ajax({
url: oDataUrl,
type: "GET",
dataType: "json",
headers: {
"accept": "application/json;odata=verbose"
},
success: successFunction,
error: errorFunction
});
}
I get current SP user with this code:
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 user = data.d.Title;
console.log(user);
}
function onError(error) {
console.log("error");
}
Now how to draw a table and use this user var in table search?
$('#example').DataTable({
search: {search: user}
});
I guess I need to combine these two ajax calls into one and then use this user var but not sure how to do it.
This question has an accepted answers - jump to answer
Answers
You've got two async actions there - getting the data and loading the user id. So the correct answer will depend upon a number of factors. Firstly, do you get the user before creating the table (i.e. will the table only initialise after the user has been obtained) or are they truly async next to each other?
If they are, then you need to account for the case where the table is loaded before the user and also for when the user is loaded before the user.
What you have is the correct way for if you have the user first. If you have the table first and then the user, then you can use the
search()
method.Allan
Actions are truly async, when there is no user in the table to filter it by, table wouldn't filter and show all the data, but if in the table is user which is current logged in user, than table will be filtered by the user.
Perfect - thanks. In that case:
Allan
Thanks for the reply. Could you please show me an example on how to do it?
I don't understand how to get a user from ajax call and use this user as filter value in DataTable initialisation...
Set it to a global variable (or some other scope that both actions have access to):
Then you just keep the code you have above:
Additionally your
onSuccess
to check for the existing DataTable would be:Allan