Fetching information via AJAX to populate a whitelist for Tagify

Attempting to retrieve data via ajax for tagify whitelist, but encountering the following error:

ReferenceError: Can't find variable: clist

Here is the code snippet:

$.ajax({
                url: '/ajaxget/tags',
                method: 'GET',
                data: {
                    <?= csrf_token() ?> : '<?=csrf_hash()?>'
                },
                success: function(response) {
                 var clist = response;
                    //alert(response);
                }
            });


    var input = document.querySelector('input[name="tags"]');

    tagify = new Tagify(input, {
        enforceWhitelist: true,
      whitelist: clist,
      maxTags: 5,
      dropdown: {
        maxItems: 5,           
        classname: "tags-look", 
        enabled: 0,             
        closeOnSelect: false    
      }
    });

Testing with "alert (response);" shows the data - ['123','333','763',asd']

Answer №1

One common mistake is attempting to use a local variable from within a callback response as a global variable.

             $.ajax({
                url: '/ajaxget/tags',
                method: 'GET',
                data: {
                    <?= csrf_token() ?> : '<?=csrf_hash()?>'
                },
                success: function(response) {
                 var tagList = response;
                    populateTags(tagList);
                }
            });

    function populateTags(tagList) {
      var inputField = document.querySelector('input[name="tags"]');

      tagsInput = new TagsInput(inputField, {
        enforceWhitelist: true,
        whitelist: tagList,
        maxTags: 5,
        dropdown: {
          maxItems: 5,           
          classname: "tags-look", 
          enabled: 0,             
          closeOnSelect: false    
        }
      });
  }

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

The toggle-input component I implemented in React is not providing the desired level of accessibility

Having an accessibility issue with a toggle input while using VoiceOver on a Mac. The problem is that when I turn the toggle off, VoiceOver says it's on, and vice versa. How can I fix this so that VoiceOver accurately states whether the toggle is on o ...

comparative analysis: nextjs getServerSideProps vs direct API calls

Trying to grasp the fundamental distinction between getServerSideProps and utilizing useSWR directly within the page component. If I implement the following code snippet in getServerSideProps: export const getServerSideProps = async () => { try { ...

Retrieve, establish cookies, and guard against CSRF attacks

Having some difficulty with CSRF in my application while using Isomorphic fetch. The backend sends a CSRF-TOKEN in the set-cookies property: https://i.sstatic.net/duODj.png There is advice against directly accessing these cookies in code, so I attempted ...

Guide on integrating HTML from a response into the render function in React JS

I've been doing some research but I'm struggling to find a good solution for this issue. I have a response that looks like this: "name": "another test", "description": "para hacer el aseo", &quo ...

Using d3.js to dynamically change the color of svg elements based on their data values

I was searching for a way to dynamically color SVG rectangles based on values from a dataset. If I were to create rectangles for each data entry, how could I adjust the rectangle's color according to the data value? Here is what I currently have: // ...

Choosing items by pressing "shift + up arrow"

I have a collection of elements, each representing one line of text. When you click on an element, it changes color. If you then hold down "shift + arrow up," the items above it are also selected. How can this functionality be implemented? My initial app ...

Applying a class change in Vue.js upon mounting

How can I make a button element with a .hover property trigger the hover animation as soon as the page loads? I want to apply a class to the button when the page is mounted and then remove it later. What is the best approach for this? I considered using a ...

Is there a way to determine if a browser's Storage object is localStorage or sessionStorage in order to effectively handle static and dynamic secret keys within a client?

I have developed a customizable storage service where an example is getExpirableStorage(getSecureStorage(getLocalStorage() | getSessionStorage())) in typescript/javascript. When implementing getSecureStorage, I used a static cipher key to encrypt every ke ...

Trouble with React Material Modal TransitionProps triggering onEntering event

Currently, I am in the process of updating Material UI to version 5. Initially, I encountered an error stating that onEntering is deprecated and should be replaced with transitionprops. There is a specific method (let's name it doSomething) that I wa ...

Show an HTML email message on a webpage without disrupting the existing page layout

Looking for a solution to display mail messages on a web page originating from an exchange server with various style elements that might interfere with the existing page layout. Attempting to load these mail messages within a div results in the style elem ...

Testing Async operations in the browser with Mocha and Chai

I'm having trouble running async tests with mocha. Below is the snippet of my code: describe('Brightcove Wrapper',function(){ describe("#init()", function() { it("Should inject the brightcove javascript", function(callback){ ...

What techniques are most effective for creating unit tests in a Node.js environment?

One of the challenges I am facing is writing a unit test for a module where I load a mustache template file. To tackle this, I am exploring the use of mocha, chai, and rewire. Below is an excerpt from my module.js: var winston = require('winston&apo ...

How can we incorporate spans into child elements using JavaScript?

Recently, I encountered a problem with a code that is supposed to add a span if it doesn't already exist on certain elements. However, the current implementation only adds the span to one element and not others because the code detects that it already ...

Guide to Embedding an Image in a List in HTML

How do I resize an image according to the size specified in CSS, and ensure that it fits within a list of items where each item consists of both an image and a name? Currently, my code only displays the image in its original size. for(var i =0; i< o ...

Encountering: error TS1128 - Expecting declaration or statement in a ReactJS and TypeScript application

My current code for the new component I created is causing this error to be thrown. Error: Failed to compile ./src/components/Hello.tsx (5,1): error TS1128: Declaration or statement expected. I've reviewed other solutions but haven't pinpointed ...

Lamenting the Perils of Losing AngularJS Rootscope Data upon Refresh

Currently, I am facing an issue in AngularJS 1.x. When I save a value in the $rootScope and pass to the next page or router, unfortunately, the $rootScope value gets lost upon refreshing the page (F5/Window Reload). I need a solution that doesn't inv ...

axios: prevent automatic sorting of objects according to keys

When using axios, I am receiving an API response. To send the sorted API response based on name, I use the following endpoint: http://localhost:8000/api/ingredients/ordering=name The actual object received from my server looks like this: { 2:{"id":2 ...

In reference to carrying out functions post partial page reload

For the web page I'm working on, I have set it up so that upon reloading, an ajax call is made to the server to retrieve and display data. Within my code, I have included: $(document).ready( function(){.... some work.... }); Now, I also have a refre ...

Utilizing AngularJS: Establishing a Universal Parent State in UI-Router for Modals and Shared Components

In my code using UI-Router and Bootstrap-ui modal, I have defined the state as shown below. reference var state = { name: 'modala', parent: 'home', onEnter: function($modal, $state) { modalInstance = $modal.open({ ...

What is the process for obtaining intersection set data from an array?

I'm trying to find the intersection set within an array only containing type 1 and 2. Can you help me with that? var arr = [ { id: 1, auths: [ { authId: 1, type: 1, value: 'Test1' }, { authId: 2, type: 1, ...