Fill out the form field using an AJAX request

Whenever a specific business is selected from a dropdown list, I want to automatically populate a Django form field.

For example:

I have a list of businesses (business A, business B, ...) and corresponding countries where each business is located.

Business A --> France
Business B --> Germany
Business C --> England

In my form, selecting a business should immediately fill in the country field with the associated country. If the business changes, the country should change accordingly.

I am working with Django 1.11.18.

The scenario:

In my code, MemberState represents the Country as shown above, and RBI represents the business.

My Model:

class MemberState(models.Model):

    name = models.CharField(max_length=256, verbose_name=_('Name'))
    code = models.CharField(max_length=256, verbose_name=_('Code'))

class RBI(models.Model):

    short_name = models.CharField(max_length=256, verbose_name=_('Short name'), unique=True)
    member_state = models.ForeignKey(MemberState, verbose_name=_('Member State'))
    ...

My Form:

class FinalProductSearchForm(forms.Form):

    releasing_body = ShortNameModelChoiceField(queryset=RBI.objects.filter(active=True).order_by('short_name'), required=False,
            widget=forms.Select(), empty_label=_('Select'), label=_('Releasing Body/Institution'))
    member_state = forms.ModelChoiceField(queryset=MemberState.objects.filter(active=True).order_by('name'), required=False,
            widget=forms.Select(), empty_label=_('Select'), label=_('Member state'))
    ...

I aim to choose a releasing_body in the form and auto-fill the associated member_state field. When switching the realeasing_body, the corresponding member_state should be loaded.

Although I tried some Django methods, I realize that AJAX requests are needed for this task - which is new to me.

Implementing AJAX:

My first attempt at implementing AJAX didn't work, here are the snippets:

In my views.py file, I added this function:

def ajax_member_state_request(request):
    if request.is_ajax():
        release_body = request.GET.get('releasing_body', None)
        print(release_body)
        member_state_ini = ReleaseBodyInstitution.objects.values_list('member_state', flat=True).get(id=release_body)
        print(member_state_ini)
        member_state = MemberState.objects.get(id=member_state_ini)
        print(member_state)
    return JsonResponse({'member_state': member_state})

In urls.py, I included:

url(r'^finalproduct/list/$', FinalProductListView.as_view(),
    name='finalproduct-list'),
url(r'^finalproduct/list/ajax_member_state_request/$', views.ajax_member_state_request, name='ajax_member_state_request'),

Lastly, in my HTML file, I included:

<form id="providerForm" data-provider-url="{% url 'ajax_member_state_request' %}" class="navbar-search" method="GET" action="{{ url }}">

{% csrf_token %}
    <div class="row">
      <div class="col-md-5">
        {{ search_form.releasing_body|as_crispy_field }}
      </div>
      <div class="col-md-5">
        {{ search_form.member_state|as_crispy_field }}
      </div>
    </div>

    <input type="submit" class="btn btn-default" value="{% trans 'Search' %}" />
    <input type="button" class="btn btn-default" name="clear" value="Reset" onclick="clearForm(this.form);">
</form>

The AJAX section looks like this:

$("#id_releasing_body").change(function () {
  var url = $("#providerForm").attr("data-provider-url");
  var releasingBodyId = $(this).val();

  $.ajax({
    url: url,
    type: 'GET',
    dataType: 'json',
    data: {
      'releasing_body': releasingBodyId
    },
    success: function (data) {
      $("#id_member_state").val(data.member_state);
    }
  });

});

Answer №1

To enhance user experience, I propose creating a feature where users can input a business name and receive a JsonResponse containing the corresponding country information.

Once this feature is implemented, in the success section of the ajax request, we can populate the country form field with the received data.

The implementation would involve:

def country_for_business(request):
    if request.is_ajax():
        member_state = ReleaseBodyInstitution.objects.get(id=release_body).member_state
    return JsonResponse({'member_state': member_state})

And for the ajax part:

$("#id_releasing_body").change(function () {
  var url = $("#providerForm").attr("data-provider-url");
  var releasingBodyId = $(this).val();

  $.get(url, {'releasing_body': releasingBodyId}, function(data){
       $("#id_member_state").text(data.member_state);
  });    
});

Answer №2

Try out this method that I used for my own project to populate choicefields with an AJAX request. The only issue I'm facing is that the form doesn't bind when submitted, even though all fields have a selected value (currently troubleshooting this).

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

Trouble with parsing dates in JavaScript using Moment.js

I'm retrieving dates from SQL Server that are passing through ASP.NET, and then iterating through a list of objects in jQuery to display the dates along with other data. However, regardless of the various date/time values coming from the database, the ...

Create a post using Google Apps Script

I have been attempting to send data from an HTML form to a Google sheet. As of now, I am stuck writing the code in Google App script and encountering an error message that says "Script function not found: doGet". Despite numerous attempts, I am unable to r ...

Embed a website in an iframe and modify a portion of the URL within the embedded page

Welcome to my first question here! I am looking for a solution that will allow me to load a webpage inside an iframe while modifying parts of the URLs in any links on the page with different text. For example, let's say we load a website like "myweb ...

PHP returns the result of form submission to JavaScript, allowing for distinction between successful and unsuccessful outcomes

JavaScript: $("#register-form").submit(function(event) { event.preventDefault(); $.post("./register.php", { username: $("#username").val(), password: $("#password").val(), passwordtwo: $("#passwordtwo").val(), email: $ ...

How can I organize a dictionary based on a specified key order in Jinja2?

Suppose I need to showcase the following data: • b is foo • a is bar • c is baz ...however, my dataset is structured like this (or any other sequence due to JSON's flexibility): { "a": "bar", "b": "foo", "c": "baz" } How can I utilize Jinja2 ...

The error message "Access-Control-Allow-Origin" header is not present when making an Ajax call to ReactJS localhost

While following the ReactJS tutorial, I set up a local server using the following commands: >npm install -g http-server >http-server -c-1 After successfully starting the local server at http://localhost:8080, I encountered an issue when trying to ...

Creating an Account with Firebase

I've created a function called signup in my web project that uses JavaScript to add a user to my Firebase database. The function works fine, but I'm encountering an issue when I try to redirect to another page at the end of the function - the use ...

Facing issue with local redis session not functioning as intended

I'm encountering an issue with my redis session not functioning properly when testing locally. EDIT: Additionally, I realized that it's failing to save a cookie when trying to set req.session[somekey] as undefined like so: req.session.user = u ...

Load an iframe with Ajax without the need to refresh the page

When utilizing ajax, I am loading iframes and they are supposed to change at specific intervals. However, the page keeps refreshing whenever the iframes change. Is there a way to prevent this constant refreshing? ...

After successfully sending a GET request to the API, the Next.js 13.4.3 website still does not reflect new posts added on the hosting platform

I am currently using Next.js version 13.4.3 in my app directory to create a blog site. However, I am facing an issue. When I run npm run build locally on my computer and then start with npm run start, the new posts are displayed normally after adding them ...

Adjust the path of an element as it decreases in size

Sorry for the weird title, but that's likely why I can't find the solution on my own. I'm experimenting with CSS animations and I want the form element to decrease in height from 100px -> 0, but I want it to collapse from the top to the ...

In JavaScript, loop through an array of arrays and combine them using the concat

If I have an array like [["a", "b"], ["c", "d"]], is there a way to iterate, reduce, map, or join this array in order to get the desired output of ["ac", "ad", "bc", "bd"]? What if the array is structured as [["a", "b"], ["c", "d"], ["e", "f"]]; how can we ...

Display a loading screen in ExpressJS until the data is fully loaded and ready for use

I am currently utilizing puppeteer to extract data from a job website, and so far everything is running smoothly. app.get('/', async (req, res) => { res.render('index', {text: 'This is the index page'}); }) Up ...

Bootstrap: when divs cover the jumbotron

I have recently started exploring bootstrap and have been using it to build a homepage for my website. However, I am facing an issue: The three images are overlapping the jumbotron section and I can't seem to figure out why. Below is the HTML code sn ...

Transcribing live content directly from the browser tab

I have a unique idea for developing a browser extension specifically for Chrome. This extension would provide live transcriptions of my team's meetings directly from an open tab in the browser. I am interested in extracting keywords, such as my name, ...

Change the behavior of an onclick event on the second click

I'm trying to make a button on my website that not only plays music when clicked but also changes the text inside the button to "Go to SoundCloud" and redirects to SoundCloud. Currently, I have been able to achieve both functions separately - redirect ...

Emphasize Expandable Sections based on Search Term

I have been working on developing an HTML page for my company that will showcase a list of contacts in an "experts list". Currently, the list is structured using collapsible DIVs nested within each other. Additionally, the HTML page features a search func ...

Typescript error: Cannot access property "status" on type "never".ts(2339)

Currently, I have a method that utilizes nextjs/auth to sign in with credentials from a form. However, I am encountering a type checking error Object is possibly 'undefined'.ts(2532) const doStuff = async (values: any) => { const result: S ...

Click to remove the ellipsis from the backbone

Some Background Info I am working on creating a feed similar to Twitter where each row expands on click to show more information. The data is fetched from a JSON file sent from the backend to the frontend, and I am using Backbone.js for rendering. My fee ...

React Router isn't displaying any content

I'm facing an issue with react-router-dom where none of my components are rendering and I just see a blank white screen. The content is not being added to my index.html template, even though there are no visible errors. Interestingly, it mentions that ...