Setting the returned value from an AJAX call as a global variable

I am currently working on an ajax function that retrieves a value from a Django function. My goal is to make this output global so that I can utilize it in a select dropdown menu. Below is the snippet of my code:

$(document).ready(function () 
{ 
  function AjaxCall(HandleData) 
  {
    return $.ajax({
    url: "/evidence_values/",
    type: "post",
    data: {'evidence':document.getElementById('evidence').value},
    success: function(data){ HandleData(data);}
                   });
  }

    $("#save").click(function(){
       AjaxCall(function(output){filter_data = output});
                               });

    function CallAjax(DataHandle) 
    {
     return $.ajax({
                  url: "/get_evidence_items/",
                  type: "post",
                  success: function(data){DataHandle(data);}
                  });
    }

    $("#evidence_selected").click(function(){
       CallAjax(function(output){items_data = output});
                                             });

In another part of index.html, you will find the select dropdown menu as shown below:

<select name="evidence_selected" id="evidence_selected" style="margin-right:20px;color:#5c89db;margin-top:20px;margin-left:40px;height: 2em;border-radius: 3px;">

<option value="selectedvidence" id="selectedvidence"name="selectedvidence">Select Evidence Number</option>

{% for item in items %}
<option value="{{item.evidence}}">{{ item.evidence }}</option>
{% endfor %}
<option id="new"value="new">New</option>

</select>

Answer №1

Would you consider incorporating your data handling function to add choices directly into the select element?

  $("#evidence_selected").append('<option value=1>' + dataStr + '</option>');

Alternatively, you could store the values in an array:

 var evidenceArray = [];
 evidenceArray.push(dataStr);

Then loop through the array using a for-each function:

$("#evidence_selected").empty();
$.each(evidenceArray , function() 
{
  $("#evidence_selected").append('<option value=1>' + this+ '</option>');
});

However, if you are updating on ajax success, it may be more efficient to directly insert rather than looping through each item.

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 initiate state transition from child component to parent component using React Hooks?

In the parent component, I have the following: const [updateQuantity, quantity] = useState(1); const handleChangeQuantity = e => { console.log(e.target.value); console.log("TEST"); updateQuantity(e.target.value); }; I the ...

Guide to altering the characteristics of a button

Here is the code for a button within My Template: <div *ngFor="let detail of details" class = "col-sm-12"> <div class="pic col-sm-1"> <img height="60" width="60" [src]='detail.image'> </div> <div ...

Having trouble launching node.js on my hosting platform

I encountered an issue while trying to set up my node.js server on a hosting platform. The server is functioning properly on Windows, but it fails to work on the hosting environment. NPM INSTALL ERROR During the installation of modules, an error occurred ...

Click a button to spin images around

Is there a way to rotate an image by 90 degrees, 180 degrees, and 360 degrees with the click of a button? <img class="test" id="image" src="images/image" alt="This is the Display Image" /> I attempted to use the following script, but was not satisf ...

Is it Appropriate for Custom React Hooks to Trigger Re-Render of Related Components?

I have just developed a custom hook that internally uses useState and useEffect. After importing this hook into another React function component called ComponentA, I noticed that ComponentA re-renders every time the state within the custom hook changes. ...

Is there a way in Angular Material to consistently display both the step values and a personalized description for each step?

Is there a way to display both numerical step values and corresponding custom text in Angular Material? I prefer having the number at the top and the descriptive text at the bottom. Check out this image for reference: https://i.stack.imgur.com/LGMIO.png ...

Require help extracting a JSON object

I am currently working with a JSON database to showcase ingredients on the webpage. For each recipe, I have a dedicated HTML page. To display the ingredients, I am hand typing them into an unordered list on the page. My challenge lies in trying to fetch t ...

What is the process for displaying the save file dialog in Safari?

I'm struggling with generating a PDF and saving it as a file in Safari using an Angular app and DocRaptor. I've tried various methods from Stack Overflow, but none seem to trigger the save file dialog. Instead, they either open the file in the cu ...

"Unable to access data from 'POST' form using node.js results in 'undefined'

My task involves sending input data from an HTML page to my localhost server. In the HTML, I am using a "form" like this: <form action="/log-in", method="POST"> <h3 style='font-family: Antic Slab; font-size: 23px;'>Log in to ...

Tips for transferring client-side data to the server-side in Angular, Node.js, and Express

Seeking a straightforward solution to a seemingly basic question. I am utilizing Angular's $http method with a GET request for a promise from a specific URL (URL_OF_INTEREST). My server runs an express script server.js capable of handling GET reques ...

Executing synchronous functions in NodeJS

I've been attempting to retrieve the number of records from a database using Node.js, but I'm running into an issue with synchronous requests. When I try to print the number inside the function, it works fine, but outside the function, it doesn&a ...

Arranging files based on the total amount of a particular category within an array of related documents

Here is the structure of my main schema: _id: id, random: random, cards: [objectId, objectId, ...] //ref to cards An example of a card in the schema: _id: id, random: random, random: random, clicks: 15. I am looking to sort the top schema base ...

Choosing a value from a dropdown automatically based on the selection of a specific value from another dropdown

Currently, I am working on a project that involves selecting a value from a dropdown menu based on the selection from another dropdown menu. var gender1 = document.querySelector("#gender1"); var gender2 = document.querySelector("#gender2"); gender1.add ...

Update the icon within the expandable display

Is there a way to change the plus sign to a minus sign in an expandable table view on click? (changing fa fa-plus to fa fa-minus) The goal is to have the plus sign displayed when the view is compressed and the minus sign displayed when it is expanded. If ...

Launch a new pop-up window with a designated keyboard language

My JavaScript code opens a new window using this syntax: window.open(URL); However, I've noticed that even when the browser's keyboard language is set to 'fa' during opening, the new window still defaults to 'en'. Is there ...

Having trouble getting jQuery with AJAX to properly store a cookie

My current challenge involves storing a cookie with the user's zip code when they log in. The PHP login method works smoothly using the "wp_login" action hook. However, I also have an AJAX login on my site. Despite having written code for it, it doesn ...

Cypress: measuring the size of a hidden array

Embarking on a lengthy journey here, so bear with me. TL:TR I've recently delved into learning Cypress and encountered an issue. I'm dealing with a highly dynamic list that sometimes may have zero elements. I need to determine its length for cer ...

Ensuring real-time updates occur every time a new record is inserted into the database

Currently, I am utilizing AJAX to retrieve data from a database. I have successfully implemented a way to display this data using AJAX and now I want to ensure that any additional data in the database is automatically added to the view as well. My dilemma ...

Display additional tiles within a compact container

I'm attempting to replicate the user interface used by foursquare! Positioning the map slightly off center like they have . I've figured out how to do one part but struggling with the second part. Initially, I loaded the map in a small div (t ...

What is preventing me from binding the array index to a model in AngularJS with two-way binding?

I'm currently facing a challenge with a seemingly simple task: I have an array of string values that I want to link to a select element's options, and then connect the index of the chosen value to a variable. However, I have found that neither us ...