Query SharePoint List Using JavaScript - javascript

I'm trying to obtain values from a SharePoint 2010 list. The List name is "SitesList" at the URL of "servername/sites/dev/Lists/SitesList/AllItems.aspx". The Columns that I would like to print on the alert message "Title" and "URL."
Once I run everything, the page loads but nothing happens at all. I can see that my web part is there and I even switched out the code to something simple like an alert message and it works. What am I doing wrong?
<script type="text/javascript">
var siteUrl = '/sites/dev/';
function retrieveListItems() {
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('SitesList');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View><Query><Where><Geq><FieldRef Name=\'ID\'/>" + "<Value Type=\'Number\'>1</Value></Geq></Where></Query><RowLimit>10</RowLimit></View>");
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded(sender, args) {
var listItemInfo = '';
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
listItemInfo += '\nID: ' + oListItem.get_id() +
'\nTitle: ' + oListItem.get_item('Title') +
'\nURL: ' + oListItem.get_item('URL');
}
alert(listItemInfo.toString());
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

It looks like you're never actually triggering the retrieveListItems function.
Try adding this at the top of you script, after the var siteUrl:
<script type="text/javascript">
var siteUrl = '/sites/dev/';
ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
function retrieveListItems() {
...
}
...
</script>
This is SharePoint specific and will wait for SP.JS to load before executing the retrieveListItems function.
This is typically a more recommended approach than jQuery's document.ready function, or native JS's self executing functions as many things happen behind the scenes with SharePoint apps after the page loads.
Hope this helps!

Related

Create and update item from one list to another in SharePoint

Using Javascript in SharePoint, I need to create a list item in listA in a siteA, then create an identical list item in a listB in siteB.
Both lists would use same content type (with the same number of columns).
If an item is created in listA for the first time, then listB would create the same item and after that only update the same item using an ID column.
This is the code I have written so far:
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(updateListItem, "sp.js");
function updateListItem() {
var siteURL = "https://phessp.webhc.hctx.net/pmo/projectsitetemplate";
var ctx = new SP.ClientContext(siteURL);
var oList = ctx.get_web().get_lists().getByTitle('Project Information');
//ProjectID is the field in current list, I am using this ID to locate the same record with same ProjecdID for update
var itemId = toString(GetUrlKeyValue('ProjectID'));
this.oListItem = oList.getItemById(itemId);
oListItem.set_item('Timeline_x0020_Description', 'My Updated Timeline');
oListItem.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
alert('Item updated!');
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
I tried multiple approaches but am having issues.

Edit Reply Message (comment) to a Discussion - SharePoint Online JavaScript

I need to do this in JavaScript since the entire solution is current in JavaScript and this is the last part.
I need to be able to update a reply message (comment) to an existing discussion. I am able to change the discussion fields but not the message fields. I know the message and the discussion are two different content types and that the reply messages are under a folder for the discussion but I don't know how to edit the reply message. (There is a utility to add the reply message but not to edit it).
This is a sample of the discussion (in the list) in which you can see there are 5 replies, I want to change the body text of one of the replies via JavaScript.
Image of the Discussion Showing Replies I would like to update
And for example, I want to change the message below:
Image of Replies that I want to change the body text
I have tried to update using this code, but it only changes the discussion and not the message.
I have a feeling I need to tell the system to go into that folder to find the message and change its body text, but I am not sure how to do this and after a 2 day search on the interwebs, I can't find an answer.
Code that does not work:
function aeditListItem() {
var clientContext = new SP.ClientContext();
var oList = clientContext.get_web().get_lists().getById('40b2fbd4-4f87-d92fb05f8044'); //ID changed to protect client
this.oListItem = oList.getItemById(getParameterByName('commentid'));
oListItem.set_item('Body', document.getElementById("ideaDetails").value.replace(/\r?\n/g, '<br />'));
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
function onQuerySucceeded() {
alert('Item Updated: ' + oListItem.get_id());
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
Many Many THANKS!
Apparently at the line:
this.oListItem = oList.getItemById(getParameterByName('commentid'));
getParameterByName('commentid') does not return the proper message id, make sure the message list item id is specified.
As a proof of concept the following example shows how to:
find a message by body
replace the message with a new body
Example
var listTitle = "Discussions";
var oldMessageBody = "";
var newMessageBody = "";
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle(listTitle);
var items = list.getItems(createMessageFindQuery('Body',oldMessageBody));
ctx.load(items);
ctx.executeQueryAsync(
function(){
if(items.get_count() == 1){
var foundItem = items.getItemAtIndex(0);
foundItem.set_item('Body',newMessageBody);
foundItem.update();
ctx.executeQueryAsync(
function(){
console.log("Updated");
},
function(sender,args){
console.log(args.get_message());
});
}
else
console.log('Not found or multiple items are found')
},
function(sender,args){
console.log(args.get_message());
});
});
function createMessageFindQuery(fieldName,fieldVal){
var qry = new SP.CamlQuery;
qry.set_viewXml(String.format('<View Scope="RecursiveAll"><Query><Where><Contains><FieldRef Name="{0}" /><Value Type="Text">{1}</Value></Contains></Where></Query></View>',fieldName,fieldVal));
return qry;
}

How to get active directory user name without domain name?

I am getting this in my SharePoint output in script editor. executions as follows:
i:0#.w|iscsharepoint\administrator
The code for this is as follows for this
<script type="text/javascript">
function GetLoggedInUserName()
{
var context = new SP.ClientContext.get_current();
this.website = context.get_web();
this.currentUser = website.get_currentUser();
context.load(currentUser);
context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded(sender, args)
{
alert(currentUser.get_loginName());
}
function onQueryFailed(sender, args)
{
alert('request failed ' + args.get_message() + '\n'+ args.get_stackTrace());
}
</script>
Now I am trying to get it this excution.
"Hi Administrator"
You can parse the username manually, like so:
var name = currentUser.get_loginName().split("\\")[1];
alert("Hi " + name);
You can also retrieve the user's actual name instead of their login name:
var name = currentUser.get_title();
alert("Hi " + name);

SCRIPT5022: The collection has not been initialized. It has not been requested or the request has not been executed

i have a simple javascript which throws me the following error:
SCRIPT5022: The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
I am using it under O365 inside an Content Editor WebPart. I have a list called "myTestList" with several items and one column called "points". I want to retrieve only the items which i have created and sum the points to show it inside a div. This is my code.
<div id="myPoints" style="font-size: 50px;">0​</div>
<script language="javascript" type="text/javascript">
SP.SOD.executeOrDelayUntilScriptLoaded(retrieveMyItems, "sp.js");
function retrieveMyItems() {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('myTestList');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='Author' /><Value Type='Integer'><UserID /></Value></Eq></Where></Query></View>");
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem, 'Include(points)');
clientContext.executeQueryAsync(Function.createDelegate(this, this.onMyItemsQuerySucceeded), Function.createDelegate(this, this.onMyItemsQueryFailed));
}
function onMyItemsQuerySucceeded(sender, args) {
var listItemInfo = 0;
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
listItemInfo = listItemInfo + parseInt(oListItem.get_item('points'));
}
var div = document.getElementById("myPoints");
div.innerHTML = listItemInfo;
}
function onMyItemsQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>​
Whats wrong here?
Update
Solved! The set_viewXml
camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='Author' /><Value Type='Integer'><UserID Type='Integer'/></Value></Eq></Query></Where></View>");
I had to add .
Update Solved! The set_viewXml
camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='Author' /><Value Type='Integer'><UserID Type='Integer'/></Value></Eq></Query></Where></View>");
had to be extend with
<Query><Where>

Create a copy of document in SharePoint 2010 document library using JavaScript

I want to create a copy of document in the SharePoint document library.
Basically let us assume there is a template and every user will open the document by clicking on it. I want to create a copy of file user has clicked and open that file for editting.
I have tried using JavaScript Client Object model of SharePoint. But the examples are for manipulating list items but not for document library.
Can any one please point to any sources that I can use to manipulate the files in document library
One restriction being I need to use JavaScript object model or web services to achive this functionality. i.e., NO server side code
Following is the code I got till now
The approach I am planning to use is copy the existing file object
Rename it and
Save it to other document library
Please ignore formatting as I am not able to do it properly and this is under development code
<script type="text/javascript">
var clientContext = null;
var web = null;
var meetingItems = null;
var filePath = null;
var file = null;
debugger;
ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
function Initialize() {
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
this.list = web.get_lists().getByTitle("Documents");
clientContext.load(list, 'Title', 'Id');
var queryStart = "<View>"+ "<Query>"+ "<Where>"+ "<Eq>"+ "<FieldRef Name='Title'/>" + "<Value Type='Text'>";
var queryEnd = "</Value>"+ "</Eq>"+ "</Where>"+ "</Query>"+ "</View>";
camlQuery = new SP.CamlQuery();
queryMeeting = queryStart + 'DevCookbook'+ queryEnd;
camlQuery.set_viewXml(queryMeeting);
meetingItems = list.getItems(camlQuery);
clientContext.load(meetingItems);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onListLoadSuccess), Function.createDelegate(this, this.onQueryFailed));
}
function onListLoadSuccess(sender, args) {
filePath = meetingItems.get_item(0).get_path();
file = meetingItems.get_item(0);
debugger;
clientContext.load(file);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onFileLoadSuccess), Function.createDelegate(this, this.onFileFailed));
// alert("List title : " + this.list.get_title() + "; List ID : " + this.list.get_id());
// doclist();
}
function doclist()
{
var path = file.get_title();
path = meetingItems.get_item(0).get_file().get_title();
}
function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
function onFileLoadSuccess(sender, args) {
debugger;
alert("List title : " + this.list.get_title() + "; List ID : " + this.list.get_id());
}
function onFileFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
I used copy webservice to do the functionality.
Approach is combination of Object Model and JavaScript functions
Copy the file from templates library.
Check out file using "CheckoutDocument" function
Add metadata in background
Show edits metadata pop up to user using
var oDialog = {
url: "../Library/Forms/Edit.aspx?ID=" + itemID,
title: "Create a new document"
};
SP.UI.ModalDialog.showModalDialog(oDialog)
After user input check in the document

Categories

Resources