Tuesday, June 17, 2014

Search documents from a Document library by calling List.asmx webservice via JavaScript

Context: The requirement from the customer was to provide a search facility on the welcome page of the site where they can find documents by adding a keyword or text. The customer doesn’t want to use the Search service provided by SharePoint and wants the dedicated component only applied to a single document library where he has thousands of documents stored.

Solution: The solution that I proposed is to create a content editor webpart which would be binded to an html page and javascript files. I used JavaScript to call the list.asmx webservice and the following code that I wrote to accomplish this task.
function SearchDocs() {

    var soapEnv =
            "" +
             "" +
             "" +
             "ListName" +
             "" +
             "" +
             "TRUE" +
             "" +
             "TRUE" +
             " " +
             " " +
             " " +
             " " +
             "" + $('#txtExactPhrase').val() + "" +
             "" + $('#txtExactPhrase').val() + " " +
             " " +
             " " +
             " " +
             " " +
             " " +
             " " +
             " " +
             " " +
             " " +
             "";


    $.ajax({
        url: "http://sharepointsite/_vti_bin/lists.asmx",
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        complete: RenderResults,
        contentType: "text/xml; charset=\"utf-8\""
    });


function RenderResults(xData, status) {
    var hdrTable = "";

    var rowTable = "";
    $(xData.responseXML).find("z\\:row").each(function () {
        var arrPath = $(this).attr("ows_FileRef").split(';#');
        var docname = ExtractValue($(this).attr("ows_FileLeafRef"), 1, ';#');
        var datelastmodified = ExtractValue($(this).attr("ows_Last_x0020_Modified"), 1, ';#');
        datelastmodified = moment(datelastmodified).format('MM/DD/YYYY HH:mm');

        var type = "";
        if ($(this).attr("ows_DocIcon") != null) {
            type = $(this).attr("ows_DocIcon");
        }
        else if ($(this).attr("ows_HTML_x0020_File_x0020_Type") != null) {
            type = "Document set";
        }
        rowTable = rowTable + "";

    });
    var renderTable = hdrTable + rowTable + "
TypeTitleNameLast Modified Date
" + type + "" + $(this).attr("ows_Title") + "" + docname + "" + datelastmodified + "
"; $("#divRenderResults").empty(); $("#divRenderResults").append(renderTable); } }
The following is how the search content editor works when a keyword is searched.


No comments:

Post a Comment