Steps to dynamically change the select options using Jquery after successfully receiving data through Ajax

Upon clicking the button, I see console output correctly; however, my options are not updating. I am a beginner in Ajax, Jquery, and Django and have spent over a week trying to resolve these issues with no success. Please assist me.

This is my Django code:

# model
class Post(models.Model):
    post_heading = models.CharField(max_length=200)
    post_text = models.TextField()

    def __str__(self):
        return self.post_heading

# view
def getmydata(request):
    # Retrieve provinces for a given country from the database without null or blank values

    if request.method == "GET":
       data = list(Post.objects.all().values())
       return JsonResponse({"data": data})

This is my HTML template:

    <div >
        <select name="car_maker" id="car_maker">
            <option value="volvo">Volvo</option>
            <option value="saab">Saab</option>
            <option value="fiat">Fiat</option>
            <option value="audi">Audi</option>
        </select>
    </div>
    <div class="postacct">
        <p>{{ acct.post_heading }}</p>
    </div>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script type="text/javascript">
    $('.clickme').click(function(){
        let catid;
        {#catid = $(this).attr("data-catid");#}
        catid='nil'
    $.ajax(
        {
            type: "GET",
            url: "/getmydata",
            data: {
                post_id: catid,
                'csrfmiddlewaretoken': '{{csrf_token}}'
            },
            success: function (data) {

                
                console.log(data);
                $("#car_maker option").remove();

                $.each(data.rows, function (index, item) { //jQuery way of iterating through a collection
                    $("#car_maker option").append($('<option>')
                        .text(item.label)
                        .attr('value', item.value));
                })
            }
        })})
    </script>
    </body>
    </html>

My console output from Ajax call:

(index):54 

{data: Array(2)}

data: Array(2)s
0: {id: 1, post_heading: "2", post_text: "two"}
1: {id: 2, post_heading: "1", post_text: "one"}
length: 2

Answer №1

I attempted to recreate the code you provided.

<select name="car_maker" id="car_maker">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="fiat">Fiat</option>
  <option value="audi">Audi</option>
</select>

Here is my interpretation:

var data = {
  "data": [{
    'id': 1,
    'post_heading': '2',
    'post_text': 'two'
  }, {
    'id': 2,
    'post_heading': '1',
    'post_text': 'one'

  }]
}

console.log(data);

$("#car_maker option").remove();

$.each(data, function(index, item) {
  console.log('test', item[0].post_heading);
  console.log('test', item[1].post_text);
  $.each(item, function(index1, item1) {
    console.log(item1.id);
    console.log(item1.post_heading);
    console.log(item1.post_text);
    $('#car_maker').append($('<option/>', {
      value: item1.id,
      text: item1.post_text
    }));
  })
});

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

Sending an array of objects in JavaScript to a controller

I have a dynamic form that I'm trying to submit to my Controller. Instead of sending just a string or an array with data, I need to pass an array of objects using ajax request after building the Javascript Array. The challenge is that when I send only ...

The JQUERY code for refreshing a div requires a timeout delay

I'm looking for a way to refresh a specific div on my website that's used for chat. Here's the code I currently have: var refreshId = setInterval(function() { $('#chat_grab').load('chat_grab.php?randval=' + Math.rand ...

The initial return value of $(document).height may be inaccurate, but is accurate upon recalculation

I am working on implementing a pop-up screen and I would like to darken the background when it opens. Below is the Javascript code: $(document).on('click', '.item', function(){ $("#popUp").css("display" , "block"); ...

Is it possible for an independent perl script to execute a function from a website's javascript?

Looking at this complex setup, I find myself in a situation where I must find a way to trigger the $.ajax function on a webpage using a separate Perl script. The scenario involves a webpage making $.ajax calls to a Perl file, which retrieves data and send ...

Issue with Kendo dropdown's optionLabel functionality malfunctioning

Check out the Kendo code snippet below for a dropdown control. I'm currently facing an issue where I am trying to display a "Please select" option in the dropdown. This code works perfectly fine for all other dropdowns except for this specific one. T ...

Confirm the presence of Cookie and save the data

I'm a beginner in the world of Javascript and Ajax, attempting to save a user's name using cookies. I have created a form where users can input their first name (identified by id = firstName). My goal is to remember this information so that the n ...

When an AJAX request is made, it can either return an array or a single object, potentially leading to

My proficiency in Javascript is definitely lacking, and I've only just begun to understand it. I have set up an AJAX call to an API using the GET method. The JSON data returned by the API is pretty standard. If I don't include an ID, I receive ...

Eliminate the CSS triggered by a mouse click

Having some difficulty toggling the switch to change the background color. Struggling with removing the applied CSS and getting it to toggle between two different colored backgrounds. Code Sample: <!Doctype html> <html lang="en"> <head> ...

Tips for implementing personalized command buttons in Kendo Grid with AJAX request utilizing JavaScript

I am struggling with implementing custom command buttons in a Kendo grid that makes an AJAX call using JavaScript to call a web API post action with dynamic parameters (start, stop, restart) behind button clicks. datasource dataSource = new ken ...

Error 504: The timeout issue occurred during an ajax call

When I make an ajax call to process a large amount of data and then reload the page upon success, I encounter a 504 Gateway Timeout error. The ajax call is initiated with the following parameters: $.ajax({ type:'POST', cache:false, a ...

Implementing JavaScript to showcase a list extracted from an API dataset

I'm currently undertaking a project where I am integrating an API from a specific website onto my own webpage. { "data": [{ "truckplanNo":"TCTTV___0D010013", "truckplanType":"COLLECTION", " ...

The issue I am facing is that whenever I use an AJAX POST request,

I encountered an issue where the ajax post method was unable to pass a parameter to the controller, as the controller parameter always appeared as Null. Index.schtml: I attempted to initiate a new view via a parameter by triggering an element in HTML and ...

Navigating from a web address to making an asynchronous request using history.js

As I work on a small website that features multiple pages with similar layouts, I often find that only the content within a specific div varies. The rest of the elements such as navigation and header remain consistent throughout. To address this, I have s ...

Error: The specified JSON path for Ajax request could not be

Although my expertise lies in C++, I must confess that my knowledge about web development is quite limited. Therefore, please bear in mind that my question requires a simple answer. Recently, I stumbled upon a fascinating C++ library for creating a web se ...

Creating a private variable to perform a select_sum query

I have defined private variables in my CodeIgniter code like this: private $table = 'phone'; private $column_order = array(null, 'name', 'price'); private $type = array('type'); private $battery_consumption = array ...

What is the best way to retrieve widget options when inside an event?

Creating a custom jQuery widget: jQuery.widget("ui.test",{ _init: function(){ $(this.element).click(this.showPoint); }, showPoint: function(E){ E.stopPropagation(); alert(this.options.dir); } } Initializing the cu ...

Exploring the differences between detecting the XMLHttpRequest object in JavaScript and using the try

When it comes to determining browser support for AJAX, I typically rely on object detection like this: if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } ...

Unique Javascript Library Focused on AJAX

Looking for a specific JavaScript library that focuses solely on AJAX functionality, such as a basic XMLHttp wrapper. ...

Struggling to get your HTML to Express app Ajax post request up and running?

I’m currently in the process of creating a Node Express application designed for storing recipes. Through a ‘new recipe’ HTML form, users have the ability to input as many ingredients as necessary. These ingredients are then dynamically displayed usi ...

Executing JavaScript code within an AJAX request

Having a problem with an AJAX function that I need help solving: PAGE A represents the main page. PAGE X represents the content loaded via AJAX. RES A represents the results from PAGE A. RES B represents the new results loaded via AJAX. PAGE A initially ...