jQuery, SharePoint Web Services and adding thumbnail to a List

We have a SharePoint list with thumbnails attached to the list items. The request was to show a thumbnail of the image that is attached. I believe this can be done via SharePoint designer, but I thought jQuery would be easier. I added a Content Editor WebPart to the top of the page. Next I inserted the jQuery code below. This code queries the SharePoint Web Services for every item (not tested on a large list), and then loops through them. If there is an attachment, jQuery takes the ID and the path to the attachment and replace the ID column (has to the first column) for the item with the tumbnail image.

The tricks were:

  1. The soapEnv has to have “<IncludeAttachmentUrls>TRUE</IncludeAttachmentUrls>”
  2. Finding the right selector to get to the ID column:
$("table.ms-listviewtable tr:has(td.ms-vb2)").find("td:first").filter(function() {
			return $(this).text().toLowerCase() == ID;
			}).html("<img src='" + url[1] + "' width=150 height=100 />");

Here is the rest of the code:

$(document).ready(function() {
querySPWebServices();
});

function querySPWebServices() {
        var soapEnv = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
		<soapenv:Body> \
		<GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
		<listName>Projects</listName> \
		<viewFields> \
		<ViewFields> \
		<FieldRef Name='Title' /> \
        <FieldRef Name='Body' /> \
		<FieldRef Name='ID' /> \
		<FieldRef Name='Attachments' /> \
		</ViewFields> \
		</viewFields> \
		<query> \
		<Query /> \
		</query> \
		<queryOptions> \
		<QueryOptions> \
		<IncludeAttachmentUrls>TRUE</IncludeAttachmentUrls> \
		</QueryOptions> \
		</queryOptions> \
		</GetListItems> \
		</soapenv:Body> \
        </soapenv:Envelope>";

        $.ajax({
        	async: false,
            url: "http://server.name.com/site/_vti_bin/lists.asmx",
            type: "POST",
            dataType: "xml",
            data: soapEnv,
            complete: processResult,
            contentType: "text/xml; charset=\"utf-8\""
        	});
};
function processResult(xData, status) {
	$(xData.responseXML).find("z\\:row").each(function() {
		if ($(this).attr("ows_Attachments") != 0) {
		var url = $(this).attr("ows_Attachments").replace(/#/g, "").split(';');
		var ID = $(this).attr("ows_ID");
		$("table.ms-listviewtable tr:has(td.ms-vb2)").find("td:first").filter(function() {
			return $(this).text().toLowerCase() == ID;
			}).html("<img src='" + url[1] + "' width=150 height=100 />");
		};
	});
};

,

2 Responses to jQuery, SharePoint Web Services and adding thumbnail to a List

  1. Jay November 4, 2011 at 1:19 pm #

    Works like a charm. This is an awesome article. This helped me save a lot of time with a thumbnail implementation.
    Appreciate for taking time and posting this. Thank you very much.

  2. jbmurphy November 4, 2011 at 1:21 pm #

    Thanks for taking the time to comment!