How to prevent a Javascript Ajax call from retrieving the same string repeatedly from an XML file?

Encountering a challenge where an Ajax call presents the same string multiple times when attempting to autofill a field. This occurs because the URL used in the Ajax call contains the string numerous times within an XML structure.

For instance, upon executing:

/tools/_api/web/lists/getbytitle('Besucheranmeldung')/Items?&$filter=substringof('Aalen', FirmaNeu)&$select=FirmaNeu

The resulting XML appears as follows:

<?xml version="1.0" encoding="utf-8"?><feed xml:base="https://mylink/tools/_api/" xmlns="http://www.w3.org/2005/Atom" ... 

https://i.sstatic.net/cXBad.png

A code snippet is utilized to generate the dropdown menu:

var requestHeaders = {
    "Accept": "application/json;odata=verbose",
    "X-RequestDigest": NWF$("#__REQUESTDIGEST").val()
};

function startAutoComplete(varTextBoxId, listname) {
    console.log("startAutoComplete called!");
    
    // Remaining code...

Is there a way to address this issue and prevent duplicate strings from appearing within the dropdown menu?

Upon logging console.log(data.d.results);, the output is as shown:

https://i.sstatic.net/mArNT.png

Answer №1

Resolved the issue by updating the code:

var requestHeaders = {
    "Accept": "application/json;odata=verbose",
    "X-RequestDigest": NWF$("#__REQUESTDIGEST").val()
};

function initializeAutoComplete(varTextBoxId, listname) {
    console.log("initializeAutoComplete function triggered!");

    NWF$("#" + varTextBoxId).autocomplete({

        source: function (request, response) {

            var query = generateQuery(request.term, listname);

            NWF$.ajax({

                url: "/tools/_api/web/lists/getbytitle('" + listname + "')/Items?&$filter=" + query,
                contentType: "application/json;odata=verbose",
                headers: requestHeaders,

                error: function (xhr, ajaxOptions, thrownError) {
                    alert("error:" + thrownError + "\n" + xhr.status);
                },

                success: function (data) {
                    var companyResults;
                    var companies = [];
                    companyResults = groupBy(data.d.results,'CompanyNew');

                    for (var i = 0; i < companyResults.length; i++ ){
                        companies[i] = companyResults[i];
                    }

                    var counter = -1;

                    response(NWF$.map(data.d.results, function (item) {


                        switch (listname) {
                            case "VisitorRegistration":
                                counter++;
                                if (counter > companyResults.length){
                                    return;
                                }
                                return {
                                    label: companies[counter],
                                    value: companies[counter],
                                    id: companies[counter],
                                    listname: listname
                                }

                                break;
                        }

                    }));

                }
            });
        },
        minLength: 2,
        select: function (event, ui) {


        },
        open: function () {
            NWF$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
        },
        close: function () {
            NWF$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
        }
    });
    
}

function generateQuery(requestString, listname) {
    var returnValue = "";

    requestString = encodeURIComponent(requestString);

    switch (listname) {

        case "VisitorRegistration":
            returnValue = "contains('" + requestString + "', CompanyNew)" + "&$select=CompanyNew";
            break;
    }
    
    return returnValue;
    
}

function groupBy(items, propertyName)
{
    var result = [];
    $.each(items, function(index, item) {
        if ($.inArray(item[propertyName], result) == -1) {
            result.push(item[propertyName]);
        }
    });
    return result;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to eliminate the design from a previously selected list item

I'm working on creating a calendar that displays 3 booking times when a user clicks on a specific day. However, I am facing an issue where the styling (green color) remains on the selected day even if the user chooses a different day. Any assistance o ...

Discovering whether an ID exists within a variable containing HTML code

I am currently attempting to determine if the ID is included in a variable containing HTML content. The ID name is being added to a DIV element through dynamic variables. strHTML = "<div id='"+var1+var2+"'>" Now, I want to verify if a sp ...

Launching a modal using a method in Vue.js that includes constantly changing content

I am currently developing a feature in my VueJs component that involves opening a modal when a certain condition becomes true, and then retrieving data from a controller to display in the modal. After searching online, I have not been able to find clear i ...

My Discord.JS bot seems to be moving at a snail's pace, and I can

Apologies for the lackluster title, I'm struggling to come up with something better. I'm currently running a self-bot (I understand it goes against the terms of service but I'm experimenting) that needs to download new files (specifically i ...

Is there a way to bring together scrolling effects and mouse movement for a dynamic user

If you want to see a scrolling effect, check out this link here. For another animation on mouse move, click on this link(here). Combining both the scrolling effect and the image movement might seem challenging due to different styles used in each templat ...

What could be causing the <img src= ' '/> tag to malfunction in Express?

While learning about HTML, I noticed that simply using img src="...." worked fine. However, when working with Express, the same code did not work! The documentation mentioned that I needed to place the images in a folder named public, require(&ap ...

Is there a specific explanation as to why ng-repeat-start is not functioning properly even with the most recent version of AngularJS?

Can someone please explain why ng-repeat-start is not functioning properly despite using the most up-to-date AngularJS version? I have included it from the CDN: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></scr ...

The HTML button with Google's material-icons appears noticeably small when displayed on mobile devices

Looking to design a basic HTML page with a button placed in the lower right corner? Check out the code below: <!DOCTYPE html> <html> <head> <title>Sample Page</title> <style> /* Styles for the container * ...

Choosing a portion of a polyline - Google Maps Application Programming Interface

Is it possible to select only a section of a polyline in a Google Map? I have markers that are added by the user and a polyline is drawn between the markers. The polyline between two markers represents the route between the two places. I want the user to b ...

Execute a PHP function when a post is clicked using JavaScript

I have a script that shows an image depending on database results. When a user clicks the image, it changes to a new one. The green_star signifies that both $user_id and $thedb_id are in the database, while the grey_star indicates they are not. I want to b ...

React Native displaying identical path

Is there a way to dynamically change routes in React Native when a button is pressed? Inside my SplashContainer component, I have the following method: handleToSignUp = () => { console.log("Running handleToSignUp") this.props.navigator.push({ ...

What could be causing the issue of angular data-binding not functioning properly in conjunction with jquery

Currently, I am working on the angular tutorial project known as angular-phonecat, and I have reached step 5. Out of sheer curiosity, I decided to replace the original angular ajax method with a jquery ajax method while keeping everything else unchanged. ...

Firebase Firestore is returning the dreaded [object Object] rather than the expected plain object

I've created a custom hook called useDocument.js that retrieves data from a firestore collection using a specific ID. However, I'm encountering an issue where it returns [object Object] instead of a plain object. When I attempt to access the nam ...

Content not refreshing when closing and reopening Highslide iframe

I am encountering an issue with Highslide where I am unable to reopen a popup with new content. Even though the contentId remains the same, the content is not being updated when the popup is reopened. Below is the code snippet that showcases the problem: ...

Please execute the npm install command to install the readline-sync package in order to fix the error in node:internal/modules/c

Having trouble installing npm readline as it keeps showing errors, even after trying different solutions. https://i.sstatic.net/LoX6L.png https://i.sstatic.net/b8b7l.jpg Tried deleting folders and uninstalling nodejs but the issue persists. Need help fi ...

Editing content: Certain challenges with generating and concentrating on a span

For the past few days, I've been grappling with a particular issue that has left me stumped. I'm hoping for some guidance or tips that will steer me in the right direction to resolve the problem. As part of my app development, I am working on a ...

AngularJS sending unsupported media type to SpringMVC controller

Encountering an error while attempting to post JSON data from an AngularJS controller to a SpringMVC controller. Despite trying various solutions found online and ensuring that the jackson library is in the classpath, the issue persists. It's worth no ...

Angular Date Filtering to Show dd-mm-yyyy Format

I am having trouble filtering the date correctly in my controller. My desired date format is Thu Mar 31 2016 05:05:00 GMT-0400 (EDT). However, when I use the code mentioned above, the results show up as 03-31-2016. This is the code snippet from my contr ...

Using UI Bootstrap modal within a directive allows for the functionality of multiple modals, with the unique feature

Check out this Plunkr to see the issue I'm facing with two modals, each within separate directives named modal-one and modal-two. The problem arises when clicking on the button for modal two, as only modal one is being opened. I suspect that the iss ...

Linking query branches without encountering the "Exceeded the number of hooks rendered during the previous render" error

This apollo client utilizes a rest link to interact with 2 APIs. The first API returns the value and ID of a record, while the second API provides additional information about the same record. I combine this information to render the content without using ...