Sunday, July 23, 2017

Call the Service from JQuery

Call the Service from JQuery

The following demonstrates how to call the service from a Script Editor Web Part using simple HTML, JavaScript and JQuery.
source: Source
  1. <script src="http://sp13.dev/SiteAssets/jquery-1.10.2.min.js"></script>
    
    <h2>SharePoint 2013: Consume a custom WCF REST service hosted in SharePoint 2013.</h2>
    <h3>This is a quick sample to demonstrate calling a custom SharePoint-hosted WCF REST service from a
        Script Editor Web Part using simple HTML, JavaScript and JQuery.
    </h3>
    
    <div>
        <br />
        <p id="message">Loading presidents...</p>
    </div>
    
    <div id="resultsPanel"></div>
    
    <script type="text/javascript">
        $(document).ready(function () {
            getPresidentsData();
        });
      
    function getPresidentsData() {
        var serviceUri = _spPageContextInfo.webAbsoluteUrl +
            "/_vti_bin/BarkesServices/PresidentsService.svc/GetAllPresidents";
        $.ajax({
            type: "GET",
            contentType: "application/json",
            url: serviceUri,
            dataType: "json",
            success:
                function (response) {
                    showPresidentsList(response);
                    $('#message').html("<a href=" + serviceUri + ">" + serviceUri + "</a>");
                },
            error:
                function (err) {
                    alert(err);
                }
        });
    }
    
    function showPresidentsList(presidentsData) {
        $.each(presidentsData, function () {
            $('#resultsPanel').append($(this)[0].Id + ' - ');
            $('#resultsPanel').append($(this)[0].FirstName + ' ');
            $('#resultsPanel').append($(this)[0].LastName + ' (');
            $('#resultsPanel').append($(this)[0].EmailAddress + ')');
            $('#resultsPanel').append('<br><br>');
        });
    }
    </script>

No comments:

Post a Comment