I'm having trouble getting a user's info using SP Services from a sub-site. Using the code below I get the error There are multiple root elements.
var employeeName = $(this).attr('ows_Employee');
var employeeInfoViewFields = '<ViewFields>\
<FieldRef Name="Title" />\
<FieldRef Name="Department" />\
<FieldRef Name="JobTitle" />\
</ViewFields>\
<Where>\
<Eq>\
<FieldRef Name="Title" />\
<Value Type="Text">' + employeeName + '</Value>\
</Eq>\
</Where>';
$().SPServices({
operation: 'GetListItems',
async: false,
listName: 'UserInfo',
// listName: 'User Information List',
CAMLViewFields: employeeInfoViewFields,
completefunc: function(xData, Status) {
// Do stuff
}
});
I eventually replaced SPServices with a standard ajax call. This works perfectly.
$.ajax({
url: "/_api/lists/getbytitle('User Information List')/items?$filter=Title eq '" + employeeName + "'&$select=Department,JobTitle",
type: "GET",
async: false,
success: function (xml) {
department = $(xml).find('d\\:Department, Department').text();
jobTitle = $(xml).find('d\\:JobTitle, JobTitle').text();
},
error: function (a, b, c) {
alert(c);
}
});
Related
In my first outing with csom and the document library, I encountered a difficult error when attempting to access a document library object property as file.File.Title using the following code.
The error is
Object reference not set to an instance of an object on server.
The code shown is what "works" for my exercise.
What step am I missing to be able to use file.File.Title instead of file.FieldValues["Title"].
The code snippet is a very primitive attempt to get a list of files in the default Document library folder. In a following iteration, I need to update the caml to retrieve a specific file.
var lib = ctx.Web.DefaultDocumentLibrary();
ctx.Load(lib);
ctx.ExecuteQuery();
var files = lib.GetItems(CreateAllFilesQuery());
ctx.Load(files);
ctx.Load(files, items => items.Include( item => item.File.Title ));
ctx.ExecuteQuery();
foreach(var file in files )
{
if(!(file.FieldValues["Title"] == null) )
{
string FileName = file.FieldValues["Title"].ToString();
if (FileName == DocumentName)
return true;
}
}
public static CamlQuery CreateAllFilesQuery()
{
var qry = new CamlQuery();
qry.ViewXml = #"<View Scope=\'FilesOnly\'>
<Query></Query>
<ViewFields>
<FieldRef Name='Title' />
<FieldRef Name='ContentType' />
<FieldRef Name='DocIcon' />
</ViewFields>
</View>";
return qry;
}
After further research, I discovered that my caml query was at fault. The syntax error was placing slashes around the Scope value. The corrected query allows me to reference file.File.Title as expected. The additional benefit is that I am only getting back files rather than files and folders.
qry.ViewXml = #"<View Scope='FilesOnly'>
<Query></Query>
<ViewFields>
<FieldRef Name='Title' />
<FieldRef Name='ContentType' />
<FieldRef Name='DocIcon' />
</ViewFields>
</View>";
is there any tool or webPart to add banners to sharepoint 2013 that support responsiveness?
You don't need anything SP specific. I've used flexslider in the past for SP and otherwise. Just use REST to populate from your list and call flexslider in the ajax success callback.
(Too long for a comment) I do on my other machine - this is a 2010 example where I used SPServices to do the same thing. Same concept - generate your markup with the response data and apply flexslider after the markup is populated.
$(document).ready(function() {
$().SPServices({
operation: "GetListItems",
async: false,
webURL: "/",
listName: "Home Slider",
CAMLViewFields: "<ViewFields><FieldRef Name='ImageLink' /><FieldRef Name='Title' /><FieldRef Name='SubTitle' />"
+ "<FieldRef Name='LinkText' /><FieldRef Name='LinkURL' /><FieldRef Name='Description' />"
+ "</ViewFields>",
completefunc: function (xData, Status) {
var myslider;
var liHtml = "";
$(xData.responseXML).SPFilterNode("z:row").each(function() {
liHtml += "<li style='background:url(" + $(this).attr("ows_ImageLink") + ") no-repeat center top;'>"
+ "<div class='slideWrap'><div class='slideInnerWrap'>"
+ "<h2>" + $(this).attr("ows_Title") + "</h2>"
+ "<a href='" + $(this).attr("ows_LinkURL") + "' class='btn btnOrange btnLarge' >"
+ $(this).attr("ows_LinkText") + "</a>"
+ "</div></div>"
+ "</li>";
});
$("#sliders").append("<ul class='slides'>" + liHtml + "</ul>");
$('.flexslider').flexslider({
directionNav: true,
animation: "slide"
});
}
});
});
I am new to caml query and have been struggling for this.
I need the last modified List Item. Only one Item.
That means it should be orderby 'modified' and rowlimit should be 1.
But only rowlimit part of my query is working. Not the orderby part.
This is my Query :
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><OrderBy><FieldRef Name=\'Modified\' Ascending="FALSE"/></OrderBy><RowLimit>1</RowLimit></Query></View>";')
I dont know where I am going wrong.
I even tried removing the Query tags in the above mentioned query.
The query is working, its getting only one record. orderby isnt working i believe.
This is in jQuery. I have written in a function and am calling that function in my Ready function.
Please help me.
Thanks.
In fact, in your example the query returns all results since query contains some errors.
The line:
camlQuery.set_viewXml('<View><Query><OrderBy><FieldRef Name=\'Modified\' Ascending="FALSE"/></OrderBy><RowLimit>1</RowLimit></Query></View>";')
should be replaced with:
camlQuery.set_viewXml('<View><Query><OrderBy><FieldRef Name="Modified" Ascending="FALSE"/></OrderBy></Query><RowLimit>1</RowLimit></View>');
Example: how to get the last item
function getLastItem(listTitle,Success,Error){
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var list = web.get_lists().getByTitle(listTitle);
var query = new SP.CamlQuery();
query.set_viewXml('<View><Query><OrderBy><FieldRef Name="Modified" Ascending="FALSE"/></OrderBy></Query><RowLimit>1</RowLimit></View>');
var items = list.getItems(query);
ctx.load(items);
ctx.executeQueryAsync(
function() {
if(items.get_count() > 0) {
var item = items.getItemAtIndex(0);
Success(item);
}
else
{
Success(null);
}
},
Error
);
}
getLastItem('Contacts',function(item){
console.log(item.get_item('Modified'));
},function(sender,args){
console.log(args.get_message());
});
Rowlimit must be put outside the query. Actually I'm using SharepointPlus (a JavaScript API to deal with Sharepoint) that creates automatically the query for me :-)
So the XML code sent to the server should look like this:
<GetListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<listName>Your list</listName>
<viewName></viewName>
<query>
<Query>
<OrderBy>
<FieldRef Name="Status" Ascending="false"></FieldRef>
</OrderBy>
</Query>
</query>
<rowLimit>1</rowLimit>
<viewFields>
<ViewFields Properties="True">
<FieldRef Name="ID"></FieldRef>
</ViewFields>
</viewFields>
<queryOptions>
<QueryOptions>
<DateInUtc>False</DateInUtc>
<Paging ListItemCollectionPositionNext=""></Paging>
<IncludeAttachmentUrls>True</IncludeAttachmentUrls>
<IncludeMandatoryColumns>False</IncludeMandatoryColumns>
<ExpandUserField>False</ExpandUserField>
<ViewAttributes Scope="Recursive"></ViewAttributes>
</QueryOptions>
</queryOptions>
</GetListItems>
Here there is a full sample, Ascending='True' or Ascending='False' it's case sensitive
<View>
<Query>
<Where>
<Eq>
<FieldRef Name='OrderNum' />
<Value Type='Number'>90696</Value>
</Eq>
</Where>
<OrderBy>
<FieldRef Name='Modified' Ascending='False'/>
</OrderBy>
</Query>
<ViewFields>
<FieldRef Name='Title' />
<FieldRef Name='ID' />
</ViewFields>
<RowLimit>10</RowLimit>
Sharepoint tips
AymKdn is correct, the OrderBy clause should be outside of the Query clause in your Caml. Here's an example:
caml.set_viewXml('<View><OrderBy><FieldRef Name="Modified" Ascending="False"/></OrderBy><RowLimit>1</RowLimit></View>');
The Query clause is used for filtering (Where clause).
Is it possible to create a form visual webpart with fields like name, email, address and submit button. After user submit data should be submitted to sharepoint custom list here custom list will have same fields like name, email, address. I created one custom list.
I search on internet but i didn't find any solutions for that. Also am new to sharepoint. If any one can provide some links it will be helpful.
Thanks
Yes, this is very possible using jQuery and AJAX.
So, lets say that, just to be brief, this is your input:
<input type='text' id='name' />
<input type='submit' id='submitdata' value='submit />
Using jquery, you would do this:
$(function(){
$('#submitdata').click(function(){
//this gets the value from your name input
var name = $('#name').val();
var list = "PutYourListNameHere";
addListItem(name, list);
});
});
function addListItem(name, listname) {
var listType = "PutTheTypeOfListHere";
// Prepping our update & building the data object.
// Template: "nameOfField" : "dataToPutInField"
var item = {
"__metadata": { "type": listType},
"name": name
}
// Executing our add
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
console.log("Success!");
console.log(data); // Returns the newly created list item information
},
error: function (data) {
console.log("Error!");
console.log(data);
}
});
}
This SHOULD work. I am not at work where my SharePoint station is, so if you are still having issues with this, let me know.
You may use SPServices also, It will work
<script type="text/javascript" src="~/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="~/jquery.SPServices-0.7.2.min.js"></script>
HTML
<input type='text' id='name' />
<input type='text' id='email' />
<input type='text' id='mobile' />
<input type='submit' id='submit' value='Submit' />
SPServices
<script type="text/javascript">
$("#submit").click(function(){
var Fname=$("#name").val();
var Email =$("#email").val();
var Mobile =$("#mobile").val();
$().SPServices({
operation: "UpdateListItems",
async: false,
batchCmd: "New",
listName: "YourCustomListName",
valuepairs: [["Fname", Fname], ["Email", Email], ["Mobile", Mobile]], //"Fname","EMail" and "Mobile" are Fields Name of your custom list
completefunc: function(xData, status) {
if (status == "success") {
alert ("Thank you for your inquiry!" );
}
else {
alert ("Unable to submit your request at this time.");
}
}
});
});
</script>
What i need is to find all list items with the same title using SPServices. I've made a CAML query from TextBox1 but have no idea what to do next. My question is: how do I change this code to accomplish my goal?
<script language="javascript" type="text/javascript">
function GetTitleMatch()
{
var Tit = $("#TextBox1").val();
$().SPServices({
operation:"GetListItems",
listName:"CustomList",
async:false,
CAMLViewFields: "<ViewFields>"+
"<FieldRef Name='Title'/>"+
"<ViewFields>",
CAMLQuery:"<Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + Tit + "</Value></Eq></Where></Query>",
completefunc:function(xData,status)
{
alert($(xData.responseXML).find('[nodeName="z\\:row"]').length);
}
});
}
</script>
click
If anyone cares, the complete code should loock something like this:
<script language="javascript" type="text/javascript">
function GetTitleMatch()
{
var Tit = $(".TextBox1").val();
alert(Tit);
var itemCount=0;
var queryText = "<Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + Tit + "</Value></Eq></Where></Query>";
alert(queryText);
$().SPServices({
operation: "GetListItems",
listName: "CustomList",
async: false,
CAMLQuery: queryText,
completefunc: function (xData, status) {
alert(xData.responseXML.xml);
itemCount = $(xData.responseXML.xml).find("rs\\:data, data").attr("ItemCount");
alert(itemCount);
$(".TextBox3").val(itemCount);
}
});
}
</script>
<a onclick="javascript:GetTitleMatch();">click</a>
All I neded to do was use .attr("ItemCount")