Wednesday, November 25, 2015

Using SPServices to Query Subsites

SPServices is really a fantastic JQuery library that is specifically designed to embrace SharePoint. My initial brush with it was positive, but then quickly put me into a difficult place to find the answer to (what I thought was) a simple question:

Can SPServices query subsite lists? 

Quick searches insisted the answer was "Yes!", but code suggestions did not prove successful. I found with some trial and error that I could query localized lists (Lists in the current site level) without any issue, but when adjusting the url for subsite lists, I would receive the xml response "Site does not exist".

To explain my scenario, I was attempting to use SPServices to reference a specific list and return a specific field from each submitted item. I narrowed my troubles to a single attribute called "webURL". Many forums (including the documentation I believe) shows the property as "webUrl", which does work and return localized list data. But only "webURL" (notice the case difference) returns data from subsite lists. After making this small, but significant discovery, my code took off!

Hope this helps someone!

<script type="text/javascript" src="jquery-1.7.2.js"></script>

<script type="text/javascript" src="jquery.SPServices-0.7.2.js"></script>



//THIS WOUlD NEED TO BE WRAPPED IN EITHER A FUNCTION OR HANDLER  

$().SPServices({

                operation: "GetListItems",

                async: false,

                listName: "[List Name]",

                webURL: "http://[site]/[subsite]",

                CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",

                completefunc: function(xData, Status) {


            //THIS IS A HANDY WAY TO CHECK THE RESPONSE AND CLARIFY FIELDS

                //alert(xData.responseText);

                      

                      $(xData.responseXML).find("z\\:row").each(function() {

                      

        var liHtml = "<li>" + $(this).attr("ows_field15") + "</li>";

        $("#taskItems").append(liHtml);

        

         });

        }

                                                

});

   

}

 

<ul id="taskItems" />