Friday, August 3, 2012

JQuery AJAX Access of SharePoint Web Services for iPad, iDevices

JQuery makes it fairly easy to access SharePoint lists using JavaScript and AJAX calls.  This is helpful when pulling information from one site to another, or when special formatting is required.
There are plenty of blog posts out there with the standard scripts, but it turns out that they fail on the iPad. Doing some research it looks like the iDevices don't return the responseXml from the AJAX call, even if xml is specified as the format. Luckily it does return the data as a string in responseText, and with a change to the code you can convert this to XML.

function isAppleDevice(){
                    return (          
                        (navigator.userAgent.toLowerCase().indexOf("ipad") > -1) ||
                        (navigator.userAgent.toLowerCase().indexOf("iphone") > -1) ||
                        (navigator.userAgent.toLowerCase().indexOf("ipod") > -1)
                    );       
}

function GetLinksData()
{
                var soapPacket = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>
                   <soapenv:Body>
                                <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>
                                <listName>LISTNAME</listName>
                                </GetListItems>
                   </soapenv:Body>
                  </soapenv:Envelope>";
                jQuery.ajax({
                  url: "SITEURL/_vti_bin/lists.asmx",
                  type: "POST",
                  dataType: "xml",
                  data: soapPacket,
                  complete: processLinksResult,
                  contentType: "text/xml; charset="utf-8""
                });
}

function processLinksResult(xData, status) {              
                // prep xml
                var xmlString;
                if (isAppleDevice()) {  // fix for iDevices
                                var myxml = xData.responseText;
                                myxml = $(myxml);
                                var oSerializer = new XMLSerializer();
                                xmlString = oSerializer.serializeToString(myxml[1]);
                } else {
                                xmlString = xData.responseXML;
                }

              
                jQuery(xmlString).find("z\:row").each(function() {
                        alert($(this).attr("ows_Title"));
              
                   });

}

1 comment:

  1. Thanks a million, saved my day! I had to make a small modification though: using $(xData.responseText) instead of just xData.responseText, otherwise the content is null.

    ReplyDelete