user989865 user989865 -3 years ago 113
reST (reStructuredText) Question

Get documents created by current user with SharePoint Online Search REST API

I need to get the modified/created document of the user currently logged into SharePoint Online using rest api. I am able to get all created documents, however, I am missing the logic to retrieve the currently user logged in and add it to the rest query. My code:


<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"></script>
<div id="mydocuments"></div>
<script type="text/javascript">
var startrow = '&startrow=0'
var rowlimit = '&rowlimit=3'

var userName = "";

var searchQuery = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?&sourceid='e7ec8cee-ded8-43c9-beb5-436b54b31e84'" + "&refinementfilters='displayauthor:equals(\"" + userName + "\")'"

$.ajax({
url: searchQuery,
method: 'GET',
headers: {
'Accept': 'application/json; odata=verbose'
},
success: onQuerySuccess,
error: onQueryFail
});

function onQuerySuccess(data) {
var items = [];

items.push("<span id='cardtitle'>" + 'My documents ' + "</span>");
if (data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results.length == 0) {
items.push("<p>" + 'No results were found' + "</p>");
} else {
$(data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results).each(function() {
var path = keyValue(this, 'Path');
var title = keyValue(this, 'Title');
items.push('<li id="' + 'listContent' + '">' + '<img src="/_layouts/15/images/icdocx.png" class="projects" />' + ' <a href="' + path + '">' + title + '</a>' + '</li>');
});

items.push("</ul>");
$("#mydocuments").html(items.join(''));
}
}

function keyValue(row, fldName) {
var ret = null;
$.each(row.Cells.results, function() {
if (this.Key == fldName) {
ret = this.Value;
}
});
return ret;
}

function onQueryFail(sender, args) {
alert('Query failed. Error:' + args.get_message());
}

</script>


So currently I am unable to figure out how to add the Current user name to this code.

Answer Source

There is a property userDisplayName in _spPageContextInfo, unfortunately it's not documented (wiki/docs). Some folks have noticed the changes: Updates to _spPageContextInfo

So:

userName = _spPageContextInfo.userDisplayName
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download