3

Consider this as my code for displaying Announcements list in a site page on my SharePoint 2010 site:

<html>
<head>
<script type="text/javascript" src="/Test_Library/js/jquery-1.9.1.min.js"></script>
<!-- <script type="text/javascript" src="http://mvms172:9999/Test_Library/js/jquery.SPServices-2014.02.min.js"> --></script>
<script type="text/javascript" src="/Test_Library/js/jquery.SPServices-2014.02.js"></script>
</head>

<body>
<table id="Announcements" border=1 width="90%" align="center">
                <tr align='left'>
                <td><strong>_Title</strong></td>
                <td><strong>_Dream_x0020_Destination</strong></td>
                <td><strong>_PPP</strong></td>
                </tr>
</table>

<SCRIPT type=text/javascript>
$(document).ready(function() {

getMyListData() ;

function getMyListData()
{                     
    var method = "GetListItems";                 

    var list = "Announcements";                      
    var fieldsToRead = "<ViewFields>" + "<FieldRef Name='Title' />" + "<FieldRef Name='Dream_x0020_Destination' />" + "<FieldRef Name='PPP' />" + "</ViewFields>";
    var query = "<Query>" + "<Where>" + "<Or>" + "<Or>" + "<Eq>" + "<FieldRef Name='Title'/><Value Type='Text'>The America</Value>" + "</Eq>" + "<Eq>" + "<FieldRef Name='Dream_x0020_Destination' /><Value Type='Text'>USA</Value>" + "</Eq>" + "</Or>" + "<IsNotNull>" + "<FieldRef Name='PPP'/>" + "</IsNotNull>" + "</Or>" + "</Where>" + "<OrderBy>" + "<FieldRef Name='PPP' Ascending='False'/>" + "</OrderBy>" + "</Query>";                         

    $().SPServices
    ({
                operation: method,
                async: false, 

                listName: list,
                CAMLViewFields: fieldsToRead,
                CAMLQuery: query,                                                                                     
                completefunc: function (xData, Status)
                 {
                     $(xData.responseXML).SPFilterNode("z:row").each(function() 
                     {
                          var _Title = $(this).attr("ows_Title");
                          var _Dream_x0020_Destination = $(this).attr("ows_Dream_x0020_Destination");
                          var _PPP =  $(this).attr("ows_PPP");

                          $("#Announcements").append("<tr align='middle'>" +
                           "<td align='left'>"+_Title+"</td>" +
                           "<td align='left'>"+_Dream_x0020_Destination+"</td>" +
                           "<td align='left'>"+_PPP+"</td>"  +                                         
                           "</tr>");
                       });
               }
   });
   };
   });

  </script>
  </body>
  </html>

Here is my CAMLQuery Builder generated Query as requested by @Nadeem :

string sQuery = @"<Query><Where><Or><Or><Eq><FieldRef Name=""Title""/><Value Type=""Text""></Value></Eq><Eq><FieldRef Name=""Dream_x0020_Destination"" /><Value Type=""Text""></Value></Eq></Or><IsNotNull><FieldRef Name=""PPP""/></IsNotNull></Or></Where><OrderBy><FieldRef Name=""PPP"" Ascending=""False""/></OrderBy></Query>";
string sViewFields = @"<FieldRef Name=""Title"" /><FieldRef Name=""Dream_x0020_Destination"" /><FieldRef Name=""PPP"" />";
string sViewAttrs = @"Scope=""Recursive""";
uint iRowLimit = 0;

var oQuery = new SPQuery();
oQuery.Query = sQuery;
oQuery.ViewFields = sViewFields;
oQuery.ViewAttributes = sViewAttrs;
oQuery.RowLimit = iRowLimit;

SPListItemCollection collListItems = oList.GetItems(oQuery);

foreach (SPListItem oListItem in collListItems)
{
}

I have created a CEWP in this site page and uploaded all my related JS and txt files in a manually created document library. I want to retrieve and display all the rows that contains data in Announcements List in a tabular format inside this CEWP created on this site page. Problem: I was able to see only hard-coded HTML content (i.e. a single row that is in body tag and td for which is already written) and none other actual rows from my Announcements List.

Following is the Error I can find by Inspect Element on Chrome Browser:

  • XMLHttpRequest cannot load http://mvms172:99999999/_vti_bin/Lists.asmx. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.send @ jquery-1.9.1.min.js:19
  • Uncaught TypeError: Cannot read property 'parentElement' of null

In the above para, the Error description, the link is incorrect (Look at the number of 9's. This is actually not allowing me to use list operations). The correct link is "http://mvms172:9999/_vti_bin/Lists.asmx". How do I correct this?

NOTE: I am new to SharePoint and would like a few pointers/feedback to why this is not working

Edit:

  • Refer Answer by @Thriggle if you don't wish to use SPServices and jQuery (or if you want to use JavaScript Client Object Model)
  • Refer Answer by @Yash Saraiya if you want a solution using SPServices and jQuery.

Both these solutions are working absolutely fine.

9
  • 1
    How are you creating the caml query. You are not specifying the value in the first two conditions. Create a query using CAML Query builder. Commented Sep 10, 2015 at 6:27
  • I have created a query using CAMLQuery Builder itself Commented Sep 10, 2015 at 6:33
  • You need to specify the value in first two conditions where you are using Eq operator. Something like <Value Type="Text">XYZ</Value> Commented Sep 10, 2015 at 6:40
  • I did entered value but still results remained same.... Check my updated code Commented Sep 10, 2015 at 6:51
  • I would try commenting out the webURL option in the call. Everything looks right to me, and based on the error message, this might be the cause. Commented Sep 10, 2015 at 11:57

4 Answers 4

2

If the list is located on the same site on which the JavaScript is running, you don't need to use SPServices and jQuery, you can use the built-in JavaScript client object model like so:

<table id="Announcements"></table>
<script>
ExecuteOrDelayUntilScriptLoaded(getMyListData,"SP.JS");
function getMyListData(){
    var listName = "Announcements";
    var clientContext = new SP.ClientContext();
    var list = clientContext.get_web().get_lists().getByTitle(listName);
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query><Where><Or><Or><Eq><FieldRef Name="Title"/><Value Type="Text">The America</Value></Eq><Eq><FieldRef Name="Dream_x0020_Destination"/><Value Type="Text">USA</Value></Eq></Or><IsNotNull><FieldRef Name="PPP"/></IsNotNull></Or></Where><OrderBy><FieldRef Name="PPP" Ascending="False"/></OrderBy></Query></View>');
    var items = list.getItems(camlQuery);
    clientContext.load(items);
    clientContext.executeQueryAsync(
        Function.createDelegate(this,function(){
            var itemEnumerator = items.getEnumerator();
            while(itemEnumerator.moveNext()){
                var item = itemEnumerator.get_current();
                var tableRow = document.createElement("tr"); // create new table row

                var title = item.get_item("Title"); // get the field value
                var titleCell = document.createElement("td"); // create new table cell
                titleCell.innerHTML = title; // populate table cell
                tableRow.appendChild(titleCell); // append cell to the table row

                var dreamDestination = item.get_item("Dream_x0020_Destination");
                var ddCell = document.createElement("td");
                ddCell.innerHTML = dreamDestination;
                tableRow.appendChild(ddCell);

                var ppp = item.get_item("PPP");
                var pppCell = document.createElement("td");
                pppCell.innerHTML = ppp;
                tableRow.appendChild(pppCell);

                document.getElementById("Announcements").appendChild(tableRow); // add the row to the table
            }
        }),
        Function.createDelegate(this,function(sender, args){ alert(args.get_message());})); // show an error message if something goes wrong

}
</script>
2
  • your code has worked wonder's for me. However, I would also appreciate your efforts to help me know how can we come to a solution using SPServices and jQuery (any modification/addition/deletion on the code asked in my question will be highly appreciated as I am looking for multiple solutions as a learner) and how both are different from each other in terms and performance and usability. Thanks again!!! Commented Sep 11, 2015 at 6:06
  • Also, How can I fetch the announcements list columns and display as HTML Table heading? Commented Sep 11, 2015 at 8:47
1

I don't think the webURL is necessary for this, I would try commenting that out to remove the CORS related error. Only reference 1 version of the SPServices file, the uncompressed or compressed, not both. You can also try making these relative links, src="Test_Library/js/jquery.SPServices-2014.02.js"

Also I see an error in this area:

var _vTitle = $(this).attr("ows_vTitle");
var _vDream_x0020_Destination = $(this).attr("ows_vDream_x0020_Destination");
var _vPPP =  $(this).attr("ows_vPPP");

Replace the following:

ows_vTitle with ows_Title
ows_vDream_x0020_Destination with ows_Dream_x0020_Destination
ows_vPPP with ows_PPP

You are referencing fields that do not exist. If this is a content editor web part solution like tagged, I would write it like:

<script type="text/javascript" src="/Test_Library/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="/Test_Library/js/jquery.SPServices-2014.02.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    var method = "GetListItems";                 
    var list = "Announcements";                      
    var fieldsToRead = "<ViewFields><FieldRef Name='Title' /><FieldRef Name='Dream_x0020_Destination' /><FieldRef Name='PPP' /></ViewFields>";
    var query = "<Query><Where><Or><Or><Eq><FieldRef Name='Title'/><Value Type='Text'>The America</Value></Eq><Eq><FieldRef Name='Dream_x0020_Destination' /><Value Type='Text'>USA</Value></Eq></Or><IsNotNull><FieldRef Name='PPP'/></IsNotNull></Or></Where><OrderBy><FieldRef Name='PPP' Ascending='False'/></OrderBy></Query>";                         

    $().SPServices
    ({
                operation: method,
                async: false, 
                listName: list,
                CAMLViewFields: fieldsToRead,
                CAMLQuery: query,                                                                                     
                completefunc: function (xData, Status){
                     $(xData.responseXML).SPFilterNode("z:row").each(function() 
                     {

                          $("#Announcements").append("<tr align='middle'>" +
                           "<td align='left'>"+$(this).attr("ows_Title")+"</td>" +
                           "<td align='left'>"+$(this).attr("ows_Dream_x0020_Destination")+"</td>" +
                           "<td align='left'>"+$(this).attr("ows_PPP")+"</td>"  +                                         
                           "</tr>");
                       });
               }
   });

   });

  </script>



<table id="Announcements" border=1 width="90%" align="center">
                <tr align='left'>
                <td><strong>_Title</strong></td>
                <td><strong>_Dream_x0020_Destination</strong></td>
                <td><strong>_PPP</strong></td>
                </tr>
</table>
8
  • I have edited as per your instructions but still the error mentioned persists. I believe something is wrong with this link (read the number of 9's) "mvms172:99999999/_vti_bin/Lists.asmx". The correct link my page should reference is "mvms172:9999/_vti_bin/Lists.asmx" to enable list operations. Can you suggest where/how can I replace this link? Commented Sep 10, 2015 at 13:11
  • updated with more info Commented Sep 10, 2015 at 13:43
  • Updated but without any results Commented Sep 10, 2015 at 13:57
  • commenting out a script reference like that isn't going to work, delete it or wrap it in <!-- --> Commented Sep 10, 2015 at 14:01
  • sorry... i have already deleted this tag in my actual code Commented Sep 10, 2015 at 14:04
1

This script is working absolutely fine. I just found out (Thanks to my boss!!!) that there was a bug with the latest SPServices version that I was using as mentioned in their documentation. Upon using the lower version, I was able to run my script well. Thanks for all your efforts and Feedbacks.

<script type="text/javascript" src="/Test_Library/js/jquery-1.11.3.js"></script>
<script type="text/javascript" src="/Test_Library/js/jquery.SPServices-0.7.1a.min.js"></script>

<div id="Announcements">
</div>

<SCRIPT type=text/javascript>
$(document).ready(function() {
//alert("called");   
//alert($().SPServices.SPGetCurrentSite());

var list = "Announcements";                      
var fieldsToRead = "<ViewFields><FieldRef Name='Title' /><FieldRef Name='Dream_x0020_Destination' /><FieldRef Name='PPP' /></ViewFields>";
//var query = "<Query>" + "<Where>" + "<Or>" + "<Or>" + "<Eq>" + "<FieldRef Name='Title'/><Value Type='Text'>The America</Value>" + "</Eq>" + "<Eq>" + "<FieldRef Name='Dream_x0020_Destination' /><Value Type='Text'>USA</Value>" + "</Eq>" + "</Or>" + "<IsNotNull>" + "<FieldRef Name='PPP'/>" + "</IsNotNull>" + "</Or>" + "</Where>" + "<OrderBy>" + "<FieldRef Name='PPP' Ascending='False'/>" + "</OrderBy>" + "</Query>";                         
var query="<Query></Query>";
$().SPServices({
    operation: "GetListItems",
    async: false, 

    listName: "Announcements",
    CAMLViewFields: fieldsToRead,
    CAMLQuery: query,                                                                                     
    completefunc: function(xData, Status)
    {
        $(xData.responseXML).find("z\\:row, row").each(function () 
        {
            //alert(xData.responseXML);
            var _Title = $(this).attr("ows_Title");
            //alert(_Title);
            var _Dream_x0020_Destination = $(this).attr("ows_Dream_x0020_Destination");
            var _PPP =  $(this).attr("ows_PPP");

            $("#Announcements").append("<tr align='middle'>" +  "<td align='left'>"+_Title+"</td>" + "<td align='left'>"+_Dream_x0020_Destination+"</td>" +"<td align='left'>"+_PPP+"</td>"  +  "</tr>");
        });
    }
});

});

Hope this helps :) :)

2
  • 1
    I'm glad you got it figured out! If you want to learn more about the SharePoint JavaScript client object model referenced in my answer, check out Microsoft's documentation and examples here: msdn.microsoft.com/en-us/library/office/…
    – Thriggle
    Commented Sep 11, 2015 at 17:52
  • @Thriggle Thank you for providing me with this link.... It was great discussing this issue with you all Commented Sep 11, 2015 at 17:55
0

First make sure that your query does indeed return the results in CAML Query Builder. Next, update the view fields code to include <ViewFields></ViewFields> that is:

var fieldsToRead = "<ViewFields><FieldRef Name='Title' />" + 
                       "<FieldRef Name='Dream_x0020_Destination' />" + 
                       "<FieldRef Name='PPP' /></ViewFields>";
1
  • the query is working fine in CAML Query Builder... also I have added the <ViewFields> Commented Sep 10, 2015 at 7:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.