CAML query to get Published items in javascript client object
Hi,
I am using the Javascript client object model.
I am trying to use the CAML query to fetch the Published items. (excluding checked-in but not published) .
I have tried the below code, but I am not able to get the published items alone. I am getting the checked-in but not published items as well.
function FetchPages() {
var clientcontext = new SP.ClientContext.get_current();
var oweb = clientcontext.get_web();
var olist = oweb.get_lists().getByTitle("Pages");
var query = new SP.CamlQuery();
query.ViewXml = "<Where>
<Eq><FieldRef Name=\"_Level\" /><Value Type=\"Integer\">1</Value></Eq></Where>";
query.set_viewXml();
pagesItems = olist.getItems(query);
clientcontext.load(NewsItems, 'Include(Title,FileLeafRef,FileDirRef)');
clientcontext.executeQueryAsync(Function.createDelegate(this, this.RenderHtmlOnSuccess), Function.createDelegate(this, this.RenderHtmlOnFailure));
function RenderHtmlOnSuccess() {
var enumerator = this.pagesItems.getEnumerator();
while (enumerator.moveNext()) {
var currentItem = enumerator.get_current();
I am getting items which are published as well as items which are checked-in but not published.
Update: I have tried this query, but the same result:
<FieldRef Name='_ModerationStatus' /><Value Type='ModStat'>0</Value></Eq>
How to fix this?
Also, I checked this:
http://mysharepointwork.blogspot.com/2011/03/get-published-version-of-list-item.html
for (int index = 0; index < item.Versions.Count; index++)
if (item.Versions[index].Level == SPFileLevel.Published)
// Got the Item
How to modify the above code for Javascript client object model?
Thanks
Hi,
Please try to modify the query statement as below and do the test again, it works in my environment:
var query = new SP.CamlQuery();
query.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'_Level\'/><Value Type=\'Integer\'>1</Value></Eq></Where></Query></View>');
pagesItems = olist.getItems(query);
Thanks
Patrick Liang
Forum Support
Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
[email protected]
Patrick Liang
TechNet Community Support
Similar Messages
-
Hi,
I am using the Javascript Client object model.
I have a custom list and a custom document library.
Custom list contains 2 columns - dlName , dlValue
The document library contains 2 folders - "folder1" , "folder2" and contains some images.
The image name starts with the "dlValue" available in the custom list
I am using a visual webpart and using javascript client object model.
I am trying to achieve the below functionality:
1) Load a dropdown with the custom list.
2) set the image based on the value in dropdown.
I have achieved the first option, I have set the dropdown, but not sure how to query the folder and set the image.
Below is the code i have used so far:
//In Visual webpart
<select id="ddlTest" >
</select>
<br/>
<div id="PreviewLayer">
<img id="imgPlaceHolder" runat="server" alt="Image" title="imgPlaceHolder" src=" " />
</div>
// In Javascript file
function RenderHtmlOnSuccess() {
var ddlTest = this.document.getElementById("ddlTest");
ddlTest.options.length = 0;
var enumerator = this.customListItems.getEnumerator();
while (enumerator.moveNext()) {
var currentItem = enumerator.get_current();
var dropdownValue = currentItem.get_item("dlValue");
ddlTest.options[ddlTest.options.length] = new Option(currentItem.get_item("dlName"), dropdownValue);
setImage(dropdownValue); // Not sure how to query the folder and set the image based on value.
// Also if dropdown value is changed, corresponding image should be shown
How to query the folder and based on dropdown value, show the image? Also, how to handle the dropdown value change?
ThanksHi,
Here are two links for your reference:
Example of how to Get Files from a Folder using Ecmascript \ Javascript client object model in SharePoint 2010
http://sharepointmantra.wordpress.com/2013/10/19/example-of-how-to-get-files-from-a-folder-using-ecmascript-javascript-client-object-model-in-sharepoint-2010/
SP2010 JSOM Client Object Model: How to get all documents in libraries including all folders recursively
http://sharepoint.stackexchange.com/questions/70185/sp2010-jsom-client-object-model-how-to-get-all-documents-in-libraries-including
In SharePoint 2013, we can also use REST API to achieve it.
http://msdn.microsoft.com/en-us/magazine/dn198245.aspx
Thanks,
Dennis Guo
TechNet Community Support
Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
[email protected]
Dennis Guo
TechNet Community Support -
Add attachments to List Item using JavaScript Client object model in SP2010
Hi All ,
I have created custom form for submitng data in list using javascript client object model/jquery .
Now I want to add option to uplaod multiple attachments to that list item also .
Is there option with client object model for uplaoding attachment.
Thanks
M
Manesh GCan you try this and let me know
using (SPSite _site = new SPSite(SPContext.Current.Site.Url))
using (SPWeb _web = _site.OpenWeb())
//Let's suppose your Item Id is 1
int ItemId = 1;
SPList oList = _web.Lists["EmployeeList"];
SPListItem _item = oList.GetItemById(ItemId);
if (FileUpload1.HasFile)
_web.AllowUnsafeUpdates = true;
Stream fs = FileUpload1.PostedFile.InputStream;
byte[] _bytes = new byte[fs.Length];
fs.Position= 0;
fs.Read(_bytes, 0, (int)fs.Length);
fs.Close();
fs.Dispose();
_item.Attachments.Add(FileUpload1.PostedFile.FileName, _bytes);
_item.Update();
_web.AllowUnsafeUpdates = false; -
CAML Query to get Items based on Year and Month From Date Column
Hi All,
* As we knew that there are default columns in calendar like Stattdate,Title,Location..etc.
* I required the CAML Query to get the list items of calender of particular Month and Year,So that I can get number of items or evetns are in Calendar
Can any one help me how can I do this using caml query
SamarHi Stuart,
Thanks for your response,I had chosen 2nd option of our above mention suggestion.But when I try to fetech the data from a calendar it is showing below error .I
had checked the below code with oter lists by changing Type to text and it worked fine.Can you please help me how can I fetech for the calulated columns
Error
"One or more field
types are not installed properly. Go to the list settings page to delete these
fields. "
Code:
string year="2014";
string month="February";
SPSite mysite = SPContext.Current.Site;
SPWeb myweb = mysite.OpenWeb();
try
SPList mylist = myweb.Lists["Calendar"];
SPQuery myquery = new SPQuery();
myquery.Query = @"<Where>
<And>
<Eq>
<FieldRef Name='Year'/>
<Value Type='Calculated'>"
+ year + @"</Value>
</Eq>
<Eq>
<FieldRef Name='Month'
/>
<Value Type='Calculated'>"
+ month + @"</Value>
</Eq>
</And>
</Where>";
SPListItemCollection totaltiems = mylist.GetItems(myquery);
Label1.Text= "Total Number of Items is "+" "+totaltiems.Count.ToString();
catch (Exception ee)
Label1.Text = ee.Message;
finally
myweb.Dispose();
Calculated Columns
Samar -
I only recently learned/read about SharePoint's JavaScript Client Object Model. I'm reading online trying to figure this out but not having much luck.
On newform.aspx (and dispform.aspx) I want to get the
current list,
the last item created, and it's attachments. I now the CAML query I need to get the last item created, but first I have to get the current list and I am not sure how to do that.
I tried this but it returns null:
SP.ListOperation.Selection.getSelectedList()Hi,
For your issue, you can get the list name from the new form url and retrieve the list last created item :
https://social.msdn.microsoft.com/Forums/office/en-US/b90a64f8-2255-41b0-9d91-78335dd4a4cf/get-list-name-from-list-url-through-javascript?forum=sharepointdevelopmentprevious
http://msdn.microsoft.com/en-us/library/office/hh185007(v=office.14).aspx
Best Regards,
Eric
Eric Tao
TechNet Community Support -
Get current item id using JavaScript Client Object Model
I have a client query that query SharePoint list Items. Lets say it is a document library. I need to get the list item id of each.
I can query the Title of the document using this syntax.
ctx.CurrentItem['Title']
But when I try
ctx.CurrentItem['ID']
for list item ID, it does not give a value. How can I solve this?Hi Malin,
If you're using the JavaScript Client Object Model, try using the SPListItem.get_item('key') method as in the example below:
<script>
ExecuteOrDelayUntilScriptLoaded(function(){
var arrIds = [];
var clientContext = new SP.ClientContext();
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query></Query></View>');
var items = clientContext.get_web().get_lists().getByTitle("Your List Title Here").getItems(camlQuery);
clientContext.load(items);
clientContext.executeQueryAsync(Function.createDelegate(this,function(){
var itemEnumerator = items.getEnumerator();
while(itemEnumerator.moveNext()){
var itemId = itemEnumerator.get_current().get_item('ID');
arrIds.push(itemId);
alert(arrIds);
}), Function.createDelegate(this, function(){
alert("something went wrong");
},"SP.js");
</script> -
CAML query to get itemcount from sharepoint list based on Month/Year
Hi,
I have a SharePoint list with date field. Now I wan't to get item count for each month in Fiscal Year using SP Services. Hence, need a CAML query to get item count . Any suggestions will be appreciated.
Thanks in Advance.When you have your month, you'll need to calculate the first day and last day of the month and convert them to the ISO using to ISOString.
startDate.toISOString();
endDate.toISOString();
function searchList(startDate, endDate) {
var nURL = "/_vti_bin/lists.asmx";
var soapEnv = "<?xml version=\"1.0\" encoding=\"utf-8\"?> \
<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"
xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">
<soap:Body> \
<GetListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">
<listName>{YourList}</listName> \
<viewFields></viewFields> \
<query><Query><Where><And><Geq><FieldRef Name='DateField'
/><Value Type='DateTime'>" + startDate +"</Value></Geq><Leq><FieldRef Name='DateField'><Value Type='Datetime'>"+endDate+"</Leq></And></Where></Query></query> \
<queryOptions><QueryOptions><ViewAttributes Scope='Recursive'/></QueryOptions></queryOptions>
</GetListItems> \
</soap:Body> \
</soap:Envelope>";
$.ajax({
url: nURL,
beforeSend: function(xhr) {
xhr.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/GetListItems");
type: "POST",
dataType: "xml",
data: soapEnv,
complete: processResults,
contentType: "text/xml; charset=utf-8"
function processResults(xData, status)
var i;
result = $(xData.responseText).find("z\\:row, row");
if (result == undefined) {
result = $(xData.responseXML).find("z\\:row, row");
$(result).each(function(i, data) {
//Magic
i++;
return i;
Brandon James SharePoint Developer/Administrator -
Fetching file size using CAML query in Javascript client object model
Hi,
I am using the Javascript client object model to retrieve contents of a document library.
I have a document library, which contains a folder "Folder1" . "Folder1" has a zip file. I would like to get the file size of the zip file.
I have tried the below code, but not sure, how to fetch the file size.
function FetchImage() {
var clientcontext = new SP.ClientContext.get_current();
var oweb = clientcontext.get_web();
var olibrary = oweb.get_lists().getByTitle(DocLibrary);
var query = new SP.CamlQuery();
query.set_folderServerRelativeUrl("Lists/DocLibrary/folder1/");
folder = olibrary.getItems(query);
clientcontext.load(folder, 'Include(Title,ContentType, FileLeafRef,FileDirRef,File)');
clientcontext.executeQueryAsync(Function.createDelegate(this, this.RenderDataOnSuccess), Function.createDelegate(this, this.RenderDataOnFailure));
function RenderDataOnSuccess() {
var ListEnumerator = this.folder.getEnumerator();
while (ListEnumerator.moveNext()) {
var currentItem = ListEnumerator.get_current();
if (_contentType.get_name() != "Folder") {
var File = currentItem.get_file();
if (File != null) {
// Fetch file size
How to fetch the file size?
Thanks<script>
function getSize()
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.upload.file.value;
var thefile = myFSO.getFile(filepath);
var size = thefile.size;
alert(size + " bytes");
</script>
http://social.msdn.microsoft.com/Forums/en-US/e5d2ff3d-01c7-4cc0-a081-29a4dfbb0fad/getting-the-sharepoint-list-attachment-size-using-javascript?forum=sharepointcustomizationlegacy -
CAML query to get task assigned to current logged in user
I want to know the CAML query to get tasks assigned to the currently logged in user
NourHi,
This is the query that worked for me
<Where>
<And>
<Or>
<Membership Type=’CurrentUserGroups’>
<FieldRef Name=’AssignedTo’ />
</Membership>
<Eq>
<FieldRef Name=’AssignedTo’ LookupId=’TRUE’ />
<Value Type=’Lookup’>123</Value>
</Eq>
</Or>
<Neq>
<FieldRef Name=’Status’ />
<Value Type=’Text’>Completed</Value>
</Neq>
</And>
</Where>
Regards,
Nishant Rana
http://nishantrana.wordpress.com https://twitter.com/#!/nishantranacrm -
How to get all previous versions page contents and other field values of a publishing page using SharePoint Client Object Model 2010?
Thanks,
OsmitaHi Osmita,
Greetings.
Here are the links that helps you. It has code attached to it.
http://social.technet.microsoft.com/Forums/sharepoint/en-US/a0d2ab40-99ba-4368-8505-1dc559ef6469/get-content-of-previous-version-of-page-sharepoint-2010?forum=sharepointgeneralprevious
http://social.technet.microsoft.com/Forums/sharepoint/en-US/faaf419f-997e-4150-9911-48cc375c3b46/how-to-get-previous-published-versions-of-publishing-pages-in-sharepoint-2010?forum=sharepointdevelopmentprevious
Please remember to click 'Mark as Answer' on the answer if it helps you -
I am using windows authentication in my web application.
My requirement is to implement a sign out button which will sign out the user without having him to close the browser and application should not ask him to login again.
I tried following two options:
1. Redirecting the user to default signout.aspx page " /_layouts/15/SignOut.aspx "
2. Using "Sign In as a different user" URL " /_layouts/15/closeConnection.aspx?loginasanotheruser=true "
In first case, user is redirected to default sign out page but he can press "Go Back to Site" link to revisit the site. Another major issue is that the user has to close the browser to sign out from the application completely, which is not desirable
in my project requirement.
In second case, the the current user is signed out of the application but if the user has saved the password in browser, he gets signed in automatically to the application.
I also came across the solution where we replace the default sign out page with a custom sign out page, but I am not sure whether it can be implemented using JavaScript Client Object Model of SharePoint.Hi
I'm basically looking for the exact answer for the query.
Meanwhile you need to go through the link mentioned below in order to understand how to do it.
Debugging and Logging Capabilities in SharePoint 2010
Indul Hassan
Microsoft Community Contributor
http://www.indulhassan.com
You Snooze.. You Lose !! -
Add multiple people using Javascript Client Object Model
I am trying to add multiple people to a SP column of type Person/Group i.e. people picker. I am able
to add one successfully using their userId, but HAVE no clue how to do that for multiple people. Here is the code for one user:
function UserDrop(e, toElement, listGuid, columnName) {
//EcmaScript Client Object Model
var ctx = new SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getById(listGuid);
var item = list.getItemById(elementId);
//columnName is of type person/group and I am adding user //whose userId is 7
item.set_item(columnName, 7);
item.update();
// asynchronous call
ctx.executeQueryAsync(
function () { toElement.innerHTML = userLinkHtml; },
function () {alert ("Error")}
return false;
This works great and I can add user whose userId is 7, however I want to add multiple people like let's say users of user Ids 7 and 8.
Any ideas or help will be greatly appreciated.
There is a thread on this one but that's from .net COM which could accessed here: http://social.msdn.microsoft.com/Forums/en-US/sharepoint2010general/thread/5183e87c-ee1d-4594-9492-0dfdf6616cce
7929Hi ,
Can somebody let me know how the same(assigning the array values to lookup value field) can be achieved with multi-select lookup value. SP.FieldLookUpValue do not have any such methods like fromUser. Please help. Please find my code block below
clientContext = new SP.ClientContext.get_current();
if (this.clientContext != undefined && clientContext != null) {
var webSite = clientContext.get_web();
oList = webSite.get_lists().getByTitle("Add New User");
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
var itemid = parseInt($.urlParam('ID'));
var item = oList.getItemById(itemid);
var users = new Array();
users.push(SP.FieldLookupValue.set_lookupId(1));
users.push(SP.FieldLookupValue.set_lookupId(2));
item.set_item('Responsibility', users);
item.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
also i cant use managed client object model.. so pls let me know how to achieve the same using javascript client object model
Ranjani.R -
Enable anonymous access for Javascript Client Object Model
In SharePoint 2010 it was possible to use the Javascript Client Object Model with anonymous access enabled by removing "GetItems" from the ClientCallableSettings.AnonymousRestrictedTypes.
In SharePoint 2013 however, it seems that an extra security barrier has been implemented. Trying to use the Javascript Client Object Model results in the following message: "Access denied. You do not have permission to perform this action or access this
resource."
After this I went on to do a little research, and it appears that Javascript Client Object Model actually relies on the REST API (please correct me if I'm mistaken), and the REST API also doesn't seem to work as an anonymous user.
So I'm in the dark here. I can't imagine that SharePoint 2013 (so heavily relying on the client object model) can't be used with anonymous access. I've also found very little documentation on anonymous access in combination with SharePoint 2013.
So, how do I enable the Javascript Client Object Model to be used with anonymous access enabled?
P.S. Needless to say, my web application is enabled for anonymous access and so is my site collection.There are really 4 things you need to do to enable anonymous access:
1. In web application level, enable anonymous.
2. In site collection level, make sure anonymous access Entire Website.
3. In Web level, set Full Permission Masks, till here, you're able to anonymously access REST APIs.
# Enable Anonymous access
$web = Get-SPWeb $url
if($web -ne $null)
Write-Host
Write-Host -ForegroundColor Yellow "Enabling Anonymous access on:" $web.Url
Write-Host
$web.AnonymousState = "On"
Write-Host -ForegroundColor Yellow "AnonymousState set to:" $web.AnonymousState
$web.AnonymousPermMask64 = "FullMask"
Write-Host -ForegroundColor Yellow "AnonymousPermMask64 set to:" $web.AnonymousPermMask64
$web.Update()
Write-Host
Below are the things to enable anonymous client object model APIs:
4. In web application level, Require Use Remote Interfaces Permission - uncheck it.
5. In web application level, Anonymous Restricted Types, remove all of them:
$app.ClientCallableSettings.AnonymousRestrictedTypes.RemoveAll() -
Getfilebyserverrelativeurl not working in Javascript client object model
Hi,
I am using the "getfilebyserverrelativeurl" to verify if the file exists. But it does not seem to work.
I am using Javascript client object model.
Below is the code used:
//ImageName = "test1.jpg" . This file does not exist in the below location
var url = oweb.get_url() + "/Lists/LibraryName/folder1/" + ImageName;
try {
var fileUrl = oweb.get_serverRelativeUrl() + "/Lists/LibraryName/folder1/" + ImageName;
oweb.getFileByServerRelativeUrl(fileUrl);
window.location = url;
catch (e) {
alert("File does not exist.");
I am not getting any errors in javascript, but the alert is not showing up.
The file does not exist in the folder, so I am expecting the alert, but in-turn it redirects to "Page not found" OOB page.
How to fix this?
ThanksHello,
I see a few odd things with that code.
Try it with the following changes and see if it makes a difference:
// declared globally
var fileName= "";
var fileurl = "";
function downloadImage(){
fileName = "image1.zip";
fileurl = SP.ClientContext.get_current().get_url() + "/LibraryName/foldername/" + fileName;
var clientcontext = new SP.ClientContext.get_current()
var oweb = clientcontext.get_web();
var ofile = oweb.getFileByServerRelativeUrl(fileurl);
clientcontext.load(ofile);
clientcontext.executeQueryAsync(Function.createDelegate(this, this.RenderDownloadfilesOnSuccess), Function.createDelegate(this, this.RenderDownloadfilesOnFailure));
function RenderDownloadfilesOnSuccess() {
window.location = fileurl;
function RenderDownloadfilesOnFailure(sender, args) {
alert(fileName + " does not exist.");
Which version of Internet Explorer are you using for debugging? The F12 developer tools will allow you to debug JavaScript and "step out" of executing JavaScript code so you can trace the problem back to where it originates in your own code
instead of debugging the resulting errors that crop up in the built-in stuff (like MicrosoftAjax.js) -
Read versions of comments field using javascript client object model
Hi,
Does someone knows how to Read versions of comments field in 'tasks' list using javascript client object model?
Thanks
ManvirHi,
According to your description, I know you want to read versions of comments field.
We can use the
SPServices to achieve it. The below code for your reference:
$().SPServices({
operation: "GetVersionCollection",
async: false,
strlistID: "tester",
strlistItemID: 1,
strFieldName: "comments",
completefunc: function (xData, Status) {
$(xData.responseText).find("Version").each(function(i) {
console.log("Name: " + $(this).attr("Information") + " Modified: " + $(this).attr("Modified"));
More information:
http://spservices.codeplex.com/releases/view/81401
Best Regards,
Dennis Guo
Maybe you are looking for
-
Remote Function Module...
Hi Folks, I have created a RFC using tcode SE37 where in im importing 2 fields from a structure and i want to return the values to a table.... while activating the RFC im getting the Following error "REPORT/PROGRAM statement missing, or program type
-
Hi, Please let me know how to get the internal order of a material? Thanks in advance.
-
Hi , How i can know which smartfrom is using in BSP application , is there any table or way for that. regards tarun
-
HT1379 Some keys won't work?
What causes some of my keys not to work?
-
'Big Join' cause tablespace exceed
Hi guys, so basically I have 2 tables and 2 view i need to use to populate data into another table table dwcustomer( customer_id varchar2 customer_key number city varchar2 state varchar2 postal_code varchar2 gender varchar2 table dwproducts( product_