0

I was given an old webpart using SP services and XML. I was requested to use Ajax. This is the first time I do this kind of conversion and I am not sure if I am doing it correctly. When I open the console there is no errors, but the code is not being injected as it is supposed to. I moved the entire code inside the ajax call and some of the HTML gets injected but it gives me this error Uncaught SyntaxError: Unexpected identifier $.when(tdResults).done(function () { So I am not sure what I am doing wrong.

<?xml version="1.0" encoding="utf-8"?>
<WebPart xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/WebPart/v2">
  <Title>LeftNav MultiTopic Accordion Webpart</Title>
  <FrameType>None</FrameType>
  <Description>TLeftNav MultiTopic Accordion Webpart</Description>
  <IsIncluded>true</IsIncluded>
  <ZoneID>wpz</ZoneID>
  <PartOrder>0</PartOrder>
  <FrameState>Normal</FrameState>
  <Height />
  <Width />
  <AllowRemove>true</AllowRemove>
  <AllowZoneChange>true</AllowZoneChange>
  <AllowMinimize>true</AllowMinimize>
  <AllowConnect>true</AllowConnect>
  <AllowEdit>true</AllowEdit>
  <AllowHide>true</AllowHide>
  <IsVisible>true</IsVisible>
  <DetailLink />
  <HelpLink />
  <HelpMode>Modeless</HelpMode>
  <Dir>Default</Dir>
  <PartImageSmall />
  <MissingAssembly>Cannot import this Web Part.</MissingAssembly>
  <PartImageLarge>/_layouts/images/mssfwp.gif</PartImageLarge>
  <IsIncludedFilter />
  <Assembly>Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
  <TypeName>Microsoft.SharePoint.WebPartPages.SimpleFormWebPart</TypeName>
  <Content xmlns="http://schemas.microsoft.com/WebPart/v2/SimpleForm"><![CDATA[<html dir="ltr" xmlns="http://www.w3.org/1999/xhtml" xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882">
<head>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css"/>    
<script type="text/javascript" src="/Style%20Library/V6/js/vendor/mdb/jquery-3.2.1.min.js"></script>
<style type="text/css">
        #topicNav select{
            display: none!important;
        }

        @media (max-width: 767px) {
            #topicNav{
                text-align:center;
            }
            #topicNav ul {
                display: none;
            }
            #topicNav select {
                display: inline-block!important;
            }
        }

        #accordionEx .accordion .card{
    border-bottom: 1px #81D4FA solid !important;
}
#accordionColumn span{
    ;
    float:right;
    margin-bottom:2.5rem;

}
#accordionColumn span:after{
    content: "\f067";
    font-family: FontAwesome;
    ;
    right: 0;
    top: 0;
    left:100%;
    color:black;
    display: block;
    width: 32px;
    height: 32px;
    line-height: 32px;
    background:#4FC3F7;
    border-radius:50%;
    vertical-align: middle;
    text-align: center;
    -webkit-transition: all .35s;
    -o-transition: all .35s;
    transition: all .35s;
}

#accordionColumn span.down:after {
    -ms-transform: rotate(135deg);
    -moz-transform: rotate(135deg);
    -webkit-transform: rotate(135deg);
    transform: rotate(135deg);
 }
    </style>
</head>
<body>
<form id="form1" runat="server">
    <section aria-label="Main Page Content" id="td">
        <div class="container py-3">
        <div class="row justify-content-center justify-content-md-end my-2">
                <div class="col-md-4 col-10 pr-1">
                    <div class="z-depth-1 bg-white pr-3" style="border-radius:4px;">
                        <input class="form-control pl-3" id="tdSearch" style="border-radius:4px;" type="text" placeholder="Search" aria-label="Search" data-search/>
                    </div>
                </div>
                <div class="col-md-1 col-2 d-flex px-0 justify-content-md-end justify-content-start">
                    <button class="btn btn-sm px-4 d-flex justify-content-center" style="background-color:#039BE5; margin-top:4px; margin-bottom:16px" type="button" data-search-button><i class="fal fa-search" style="font-size:24px"></i></button>
                </div>
            </div>
            <div class="row justify-content-between">
                <div class="col-md-3 col-12 pr-md-4">
                    <h4 class="pb-md-3 font-weight-bold text-center text-md-left">CATEGORY</h4>
                    <div id="topicNav" class="pb-md-3 py-md-0">
                        <ul class="px-0" id="topicOptions" style="list-style-type:none; border-left:solid medium #eaeaea;">
                            <!--Options injected here-->
                        </ul>
                    </div>
                </div>
                <div class="col-md-9 col-12 pt-3 pt-md-0 px-3 px-md-0">
                    <h2 id="tdTopicTitle" class="pb-3 font-weight-bold text-center text-md-left text-uppercase">Airlines</h2>
                <!-- Grid row -->
                    <div class="row d-flex justify-content-center">

                        <!-- Grid column -->
                        <div class="col-md-12 pb-5 mr-1" id="accordionColumn">

                        </div>
                        <!-- Grid column -->

                    </div>
                    <!-- Grid row -->
                </div>
            </div>    
        </div>
    </section>  
</form>
<script type="text/javascript" src="/Style%20Library/V6/js/vendor/mdb/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
//Webpart Scripts

var accID = 'AIRLINES';
var searchVal = '';
$(document).ready(function () {

    tdResults = $().SPServices.SPGetListItemsJson({
        webURL: "/airport/business",
        listName: "TenantDirectory",
        viewName: "",
        CAMLQuery: "",
        CAMLViewFields: "",
        CAMLRowLimit: "",
        CAMLQueryOptions: "",
        changeToken: "",
        contains: "",
        mapping: {
            ows_Title: {
                mappedName: "Title",
                objectType: "Text"
            },
            ows_Address: {
                mappedName: "Address",
                objectType: "Text"
            },
            ows_Numbers: {
                mappedName: "Numbers",
                objectType: "Text"
            },
            ows_Categories: {
                mappedName: "Categories",
                objectType: "Text"
            },
            ows_link: {
                mappedName: "Link",
                objectType: "Text"
            },
            ows_ID: {
                mappedName: "ID",
                objectType: "Text"
            },

        },
        mappingOverrides: null,
        debug: false
    });

    $.when(tdResults).done(function () {
        var thistdResults = this.data;
        function onlyUnique(value, index, self) {
            return self.indexOf(value) === index;
        }
        var tdItems = $.each(thistdResults, function (ind, tdItems) {
            return tdItems;
        });

        var allTopics = [];
        for (i = 0; i < tdItems.length; i++) {
            var filterTopics = tdItems[i];
            allTopics.push(filterTopics.Categories);
        };
        allTopics.sort();

        var topicList = allTopics.filter(onlyUnique);
        for (i = 0; i < topicList.length; i++) {
            var topicName = topicList[i]
            $('#topicOptions').append('<li class="py-1 pl-3"><a href="#" class="text-dark">' + topicName + '</a></li>');
        }
        var effectIn = function () {
            $('#tdTopicTitle').html(accID).fadeTo(500, 1);
            return $("#accordionColumn").fadeTo(500, 1);
        };

        var effectOut = function () {
            $('#tdTopicTitle').fadeTo(500, 0);
            return $("#accordionColumn").fadeTo(500, 0);
        };
        //includes Polyfill
        if (!String.prototype.includes) {
          Object.defineProperty(String.prototype, 'includes', {
            value: function(search, start) {
              if (typeof start !== 'number') {
                start = 0
              }

              if (start + search.length > this.length) {
                return false
              } else {
                return this.indexOf(search, start) !== -1
              }
            }
          })
        }
        function createAccordion() {
            var tdItems = $.each(thistdResults, function (ind, tdItems) {
                return tdItems;
            });
            if (accID != 'Search Results'){
                var filterTopic = tdItems.filter(function (e) {
                    return e.Categories.toUpperCase() == accID;
                });
            }else{
                var filterTopic = tdItems.filter(function (e) {
                    var questions = e.Title.toLowerCase();
                    return questions.includes(searchVal);
                });
            }
            var buildAcc = function () {
                var accID2 = accID.replace(/\s/g, '');
                var accBuild = '<div class="accordion" id="' + accID2 + '" role="tablist" aria-multiselectable="true""></div>'
                $("#accordionColumn").append(accBuild);
            };
            buildAcc();
            var buildCards = function () {
                if(filterTopic.length !== 0){
                    for (i = 0; i < filterTopic.length; i++) {
                        var accID2 = accID.replace(/\s/g, '');
                        var tdItems = filterTopic[i];
                        var headerID = "heading" + tdItems.ID;
                        var cardBodyID = "collapse" + tdItems.ID;
                        var cardTitle = tdItems.Title;
                        if (tdItems.Address){
                            var cardAdd = '<p><strong>Address:</strong> ' + tdItems.Address + '</p>'
                        }else{
                            var cardAdd = ''
                        }
                        if(tdItems.Numbers){
                            var cardNumbers = '<p><strong>Numbers:</strong><br/> ' + tdItems.Numbers + '</p>'                   
                        }else{
                            var cardNumbers = ''
                        }
                        if (tdItems.Link){
                            var cardWebsite = tdItems.Link.slice(0, -1);
                            var website = '<p><strong>Website:</strong> <a href="'+ cardWebsite +'" target="_blank">'+ cardWebsite +'</a></p>' 
                        }else{
                            var website = ''
                        }   
                        var cardBuild = '<div class="card">' +
                            '<div class="card-header pb-1 pl-0" role="tab" id="' + headerID + '">' +
                            '<a class="collapsed" data-toggle="collapse" data-parent="#' + accID2 + '" href="#' + cardBodyID + '" aria-expanded="false" aria-controls="' + cardBodyID + '">' +
                            '<h5 class="mb-0 font-thin">' + cardTitle + '<span class="rotate"></span></h5>' +
                            '</a>' +
                            '</div>' +
                            '<div id="' + cardBodyID + '" class="collapse" role="tabpanel" aria-labelledby="' + headerID + '" data-parent="#' + accID + '">' + 
                            '<div class="card-body py-1 pl-0">' + cardAdd + cardNumbers + website + '</div>'+
                            '</div>' +
                            '</div>'
                        $(".accordion").append(cardBuild);
                    };
                    }else{
                        var cardBuild = '<h4>There are no results matching your search.</div>'
                        $(".accordion").append(cardBuild);
                    }
                        //Accordion Icon Animation
                    $('.accordion > div > div > a').on('click', function () {
                        $(this).find(".rotate").addClass("down");
                    });
                    $('.accordion > div > div > a').on('click', function () {
                        $(this).find(".rotate").addClass("down");
                    });
                };
            buildCards();

        };
        createAccordion();
        $("#topicOptions > li:first-child > a").parent().css({
            borderLeft: "solid medium #039BE5",
            marginLeft: "-3px"
        });

        $("#topicOptions > li > a").on("click", function () {
            event.returnValue = false;
            accID = this.innerHTML.toUpperCase();
            $("[data-search]")[0].value = '';
            $("#topicOptions > li").css({
                borderLeft: "none",
                marginLeft: "0px"
            });
            $(this).parent().css({
                borderLeft: "solid medium #039BE5",
                marginLeft: "-3px"
            });
            $.when(effectOut()).done(function () {
                $(".accordion").remove();
                createAccordion();
                effectIn();
            });
        });

        function topicNav() {
            // Create the dropdown base
            $("<select style=\"border:none; height:50px;\" class=\"browser-default custom-select w-100 z-depth-1\" />").appendTo("#topicNav");
            // Create default option "Go to..."
            $("<option />", {
                "selected": "",
                "value": "Choose a Topic",
                "text": "Choose a Topic"
            }).appendTo("#topicNav select");

            // Populate dropdown with menu items
            $("#topicNav > ul > li > a").each(function () {
                var topicsSelect = $(this);
                $("<option />", {
                    "value": topicsSelect.text(),
                    "text": topicsSelect.text()
                }).appendTo("#topicNav select");
            });

            // To make dropdown actually work
            // To make more unobtrusive: https://css-tricks.com/4064-unobtrusive-page-changer/
            $("#topicNav select").change(function () {
                accID = $(this).find("option:selected").val()
                $.when(effectOut()).done(function () {
                    $(".accordion").remove();
                    createAccordion();
                    effectIn();
                });
            });


        };
        topicNav();

        //Search Function
        $('[data-search]').keypress(function(event) {
            if (event.which == 13){
            event.preventDefault();
            event.returnValue = false;
            accID = 'Search Results';

            searchVal = $(this).val().toLowerCase();
                $.when(effectOut()).done(function () {
                    $("#topicOptions > li").css({
                        borderLeft: "none",
                        marginLeft: "0px"
                    });

                    $(".accordion").remove();
                    createAccordion();
                    effectIn();
                });
            }
        });
        $('[data-search-button]').on('click', function(event) {
            event.preventDefault();
            event.returnValue = false;
            accID = 'Search Results';

            $("#topicOptions > li").css({
                borderLeft: "none",
                marginLeft: "0px"
            });

            searchVal = $('#tdSearch').val().toLowerCase();
                $.when(effectOut()).done(function () {
                    $("#topicOptions > li").css({
                        borderLeft: "none",
                        marginLeft: "0px"
                    });

                    $(".accordion").remove();
                    createAccordion();
                    effectIn();
                });
        });
    });
});
    webpartMove = $("#td")
    webpartMove.detach();
    webpartMove.appendTo("#fullPageContent");
    $("#fullPageContent > div > div.row.pt-3.mb-r").removeClass('mb-r pt-3');

</script>
</body>
</html>]]></Content>
</WebPart>

This is what I have done so far.

var accID = 'AIRLINES';
var searchVal = '';

var tdResults = $.ajax({
    url: apiUrl1,
    method: 'GET',
    headers: {
        'Accept': 'application/json; odata=verbose'
    },
    success: function (data) {

        var items = data.d.results;

        for (var i = 0; i < items.length; i++) {

            var title = items[i].Title;
            var address = items[i].Address;
            var number = items[i].Numbers;
            var categories = items[i].Categories;
            var id = items[i].ID;
            var link = items[i].Link;

        } // this ends for loop

        /*mappingOverrides: null,
        debug: false*/

    }, // this ends success function

    error: function(data) {
        console.log('Error: ' + data);
    }
}); //end of ajax

    $.when(tdResults).done(function () {
        var thistdResults = this.data;
        function onlyUnique(value, index, self) {
            return self.indexOf(value) === index;
        }
        var tdItems = $.each(thistdResults, function (ind, tdItems) {
            return tdItems;
        });

        var allTopics = [];
        for (i = 0; i < tdItems.length; i++) {
            var filterTopics = tdItems[i];
            allTopics.push(filterTopics.Categories);
        };
        allTopics.sort();

        var topicList = allTopics.filter(onlyUnique);
        for (i = 0; i < topicList.length; i++) {
            var topicName = topicList[i]
            $('#topicOptions').append('<li class="py-1 pl-3"><a href="#" class="text-dark">' + topicName + '</a></li>');
        }
        var effectIn = function () {
            $('#tdTopicTitle').html(accID).fadeTo(500, 1);
            return $("#accordionColumn").fadeTo(500, 1);
        };

        var effectOut = function () {
            $('#tdTopicTitle').fadeTo(500, 0);
            return $("#accordionColumn").fadeTo(500, 0);
        };
        //includes Polyfill
        if (!String.prototype.includes) {
          Object.defineProperty(String.prototype, 'includes', {
            value: function(search, start) {
              if (typeof start !== 'number') {
                start = 0
              }

              if (start + search.length > this.length) {
                return false
              } else {
                return this.indexOf(search, start) !== -1
              }
            }
          })
        }
        function createAccordion() {
            var tdItems = $.each(thistdResults, function (ind, tdItems) {
                return tdItems;
            });
            if (accID != 'Search Results'){
                var filterTopic = tdItems.filter(function (e) {
                    return e.Categories.toUpperCase() == accID;
                });
            }else{
                var filterTopic = tdItems.filter(function (e) {
                    var questions = e.Title.toLowerCase();
                    return questions.includes(searchVal);
                });
            }
            var buildAcc = function () {
                var accID2 = accID.replace(/\s/g, '');
                var accBuild = '<div class="accordion" id="' + accID2 + '" role="tablist" aria-multiselectable="true""></div>'
                $("#accordionColumn").append(accBuild);
            };
            buildAcc();
            var buildCards = function () {
                if(filterTopic.length !== 0){
                    for (i = 0; i < filterTopic.length; i++) {
                        var accID2 = accID.replace(/\s/g, '');
                        var tdItems = filterTopic[i];
                        var headerID = "heading" + tdItems.ID;
                        var cardBodyID = "collapse" + tdItems.ID;
                        var cardTitle = tdItems.Title;
                        if (tdItems.Address){
                            var cardAdd = '<p><strong>Address:</strong> ' + tdItems.Address + '</p>'
                        }else{
                            var cardAdd = ''
                        }
                        if(tdItems.Numbers){
                            var cardNumbers = '<p><strong>Numbers:</strong><br/> ' + tdItems.Numbers + '</p>'                   
                        }else{
                            var cardNumbers = ''
                        }
                        if (tdItems.Link){
                            var cardWebsite = tdItems.Link.slice(0, -1);
                            var website = '<p><strong>Website:</strong> <a href="'+ cardWebsite +'" target="_blank">'+ cardWebsite +'</a></p>' 
                        }else{
                            var website = ''
                        }   
                        var cardBuild = '<div class="card">' +
                            '<div class="card-header pb-1 pl-0" role="tab" id="' + headerID + '">' +
                            '<a class="collapsed" data-toggle="collapse" data-parent="#' + accID2 + '" href="#' + cardBodyID + '" aria-expanded="false" aria-controls="' + cardBodyID + '">' +
                            '<h5 class="mb-0 font-thin">' + cardTitle + '<span class="rotate"></span></h5>' +
                            '</a>' +
                            '</div>' +
                            '<div id="' + cardBodyID + '" class="collapse" role="tabpanel" aria-labelledby="' + headerID + '" data-parent="#' + accID + '">' + 
                            '<div class="card-body py-1 pl-0">' + cardAdd + cardNumbers + website + '</div>'+
                            '</div>' +
                            '</div>'
                        $(".accordion").append(cardBuild);
                    };
                    }else{
                        var cardBuild = '<h4>There are no results matching your search.</div>'
                        $(".accordion").append(cardBuild);
                    }
                        //Accordion Icon Animation
                    $('.accordion > div > div > a').on('click', function () {
                        $(this).find(".rotate").addClass("down");
                    });
                    $('.accordion > div > div > a').on('click', function () {
                        $(this).find(".rotate").addClass("down");
                    });
                };
            buildCards();

        };
        createAccordion();
        $("#topicOptions > li:first-child > a").parent().css({
            borderLeft: "solid medium #039BE5",
            marginLeft: "-3px"
        });

        $("#topicOptions > li > a").on("click", function () {
            event.returnValue = false;
            accID = this.innerHTML.toUpperCase();
            $("[data-search]")[0].value = '';
            $("#topicOptions > li").css({
                borderLeft: "none",
                marginLeft: "0px"
            });
            $(this).parent().css({
                borderLeft: "solid medium #039BE5",
                marginLeft: "-3px"
            });
            $.when(effectOut()).done(function () {
                $(".accordion").remove();
                createAccordion();
                effectIn();
            });
        });

        function topicNav() {
            // Create the dropdown base
            $("<select style=\"border:none; height:50px;\" class=\"browser-default custom-select w-100 z-depth-1\" />").appendTo("#topicNav");
            // Create default option "Go to..."
            $("<option />", {
                "selected": "",
                "value": "Choose a Topic",
                "text": "Choose a Topic"
            }).appendTo("#topicNav select");

            // Populate dropdown with menu items
            $("#topicNav > ul > li > a").each(function () {
                var topicsSelect = $(this);
                $("<option />", {
                    "value": topicsSelect.text(),
                    "text": topicsSelect.text()
                }).appendTo("#topicNav select");
            });

            // To make dropdown actually work
            // To make more unobtrusive: https://css-tricks.com/4064-unobtrusive-page-changer/
            $("#topicNav select").change(function () {
                accID = $(this).find("option:selected").val()
                $.when(effectOut()).done(function () {
                    $(".accordion").remove();
                    createAccordion();
                    effectIn();
                });
            });


        };
        topicNav();

        //Search Function
        $('[data-search]').keypress(function(event) {
            if (event.which == 13){
            event.preventDefault();
            event.returnValue = false;
            accID = 'Search Results';

            searchVal = $(this).val().toLowerCase();
                $.when(effectOut()).done(function () {
                    $("#topicOptions > li").css({
                        borderLeft: "none",
                        marginLeft: "0px"
                    });

                    $(".accordion").remove();
                    createAccordion();
                    effectIn();
                });
            }
        });
        $('[data-search-button]').on('click', function(event) {
            event.preventDefault();
            event.returnValue = false;
            accID = 'Search Results';

            $("#topicOptions > li").css({
                borderLeft: "none",
                marginLeft: "0px"
            });

            searchVal = $('#tdSearch').val().toLowerCase();
                $.when(effectOut()).done(function () {
                    $("#topicOptions > li").css({
                        borderLeft: "none",
                        marginLeft: "0px"
                    });

                    $(".accordion").remove();
                    createAccordion();
                    effectIn();
                });
        });
    });

    webpartMove = $("#td")
    webpartMove.detach();
    webpartMove.appendTo("#fullPageContent");
    $("#fullPageContent > div > div.row.pt-3.mb-r").removeClass('mb-r pt-3');

</script>
  • If it works, then you're doing it right. Sorry, but that's about the best answer you're going to get for pasting in 400 lines of code devoid of any context and asking if it's right. If you have a more specific question then ask that instead. – Derek Gusoff Sep 12 at 18:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.