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

Guide for integrating images in React Native

I am struggling to display images in a carousel properly. I attempted to require them using JSON like this {"Image": require("$PATH")} or in a js file within the ParallaxImage tag, but nothing seems to work... Item Creator _renderItem ...

"An issue with PHP not receiving any data from AJAX POST request

I've been working on creating a login using AJAX. The issue I'm facing is that when the AJAX function posts data to the PHP file, the data is empty when trying to retrieve it in PHP. Here is my AJAX posting code: function validateUser() { var ...

Retrieve the JSON response from the server and store it in variables using jQuery's AJAX function with the `done

I am trying to retrieve a JSON response from the server upon clicking a button and then parse it into a div. However, I am struggling with how to accomplish this. <button type="submit" id="btPay" name="btPay"> Go for Pay ...

JQuery validation for phone number format 01x-xxxxxxxx

Currently, I am using jQuery Validate to validate the form. In order to validate the phone number field, I have implemented the following code: The phone number should be written in the format 01x-xxxxxxxx var phonereg = /^[0-9]{3}\-[0-9]{7}$/; H ...

Setting up user roles using Firebase Auth in NextJS application

Seeking a solution to implement a multi-level role system for my blog website. Currently utilizing Firebase Auth for authentication with email/password, but all users have the same posting/editing access. Looking to differentiate between Admins, Moderators ...

Difficulty redirecting Ajax call to a timed-out, CAS-protected server

Our website's login system utilizes CAS for single sign-on. The CAS server is operating the JASIG CAS server at , while our web server runs on Rails at . Due to security reasons, the Rails server has a relatively short session timeout, resulting in o ...

conceal a division beneath a YouTube video frame upon clicking

I need to hide the 'div .blind' element when a YouTube video (inside 'div #player') is clicked. How can I achieve this? Here's an example: JS: ... var player; function onYouTubeIframeAPIReady() { player = new YT.Player('pl ...

Exploring the angular js repeater component's context menu options

In one of my current projects, the client has specifically requested a right-click menu feature. However, the challenge lies in ensuring that the function triggered by the menu options has access to relevant information from the model. For instance, you ...

When utilizing AJAX, certain web pages may contain a querystring

Encountering an issue with ajax when using query strings. Data can be successfully sent when the page does not have any query string and Info.aspx/Save works perfectly fine. However, when I include query strings and post the same data, it results in a HTTP ...

ReactForms Deprication for NgModel

According to Angular, certain directives and features are considered deprecated and could potentially be removed in upcoming versions. In a hypothetical scenario, let's say I am using NgModel with reactive forms, which Angular has marked as deprecate ...

I am interested in displaying all the items on the list instead of just one

<html> <head> <link rel="stylesheet" type="text/css" href="mango.css"> <script> function showItems(){ var items = document.querySelectorAll("#main li"); items.forEach(i ...

Uploading with Javascript CORS consistently ends with an error event occurring

My current challenge is uploading a file to a server using JavaScript in compliance with the CORS specification. While there are numerous examples available online that successfully upload the file, I encounter an error as the final event being fired. Up ...

Vue3 and Ionic combined to create a Component that became a reactive object in Vue

Vue is issuing a warning about receiving a Component as a reactive object, which can cause unnecessary performance overhead. The warning suggests using markRaw or shallowRef instead of ref to avoid this issue. However, in my code, I am not explicitly using ...

What is the best way to use checkboxes in VueJS to apply filters on a loop and display specific results?

I'm struggling with implementing filters using checkboxes on a list of results and could really use some assistance. Currently, only the 'All' option is working for applying any filtering logic. Here is how my HTML looks like with the filt ...

Adjust css style based on the current time of day

I recently came across this fascinating tutorial that demonstrates an animation changing from day to night every 30 minutes. The concept is very appealing, but I began contemplating how to adapt this animation to reflect real-time changes between day and ...

Have you ever wondered why req.body returns as undefined when using body parser?

Every time I attempt to make a post request, I keep receiving an error message stating that req.body is returning as undefined. Below is the content of my server.js file: import express from 'express'; import bodyParser from 'body-parser&ap ...

What's the best way to transfer a variable from a PHP file to a jQuery AJAX file so that it can be used as the URL parameter when sending

I am just starting out with javascript, jquery, and ajax. Unfortunately, I've encountered an issue where my code is not working as expected. Below, you can find a detailed description of my code and the problem at hand. If someone could offer some ass ...

The magic of Angular's data binding post-ajax retrieval

My situation is as follows: /items/item/123/edit and I have a controller that combines both the view and edit functionalities: ... if ($routeParams.id) { $scope.itemId = $routeParams.id; $scope.editMode = true; Item.getB ...

An issue arose during the page prerendering process for "/" on Vercel | Next.js resulting in a deployment error

When attempting to deploy my website using Vercel and generating static pages, I encountered the following error in the logs: info - Generating static pages (0/6) Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/ ...

Hiding content in HTML with the Display:none property

After exploring various posts on this topic, I am still unable to find a solution that fits my specific scenario. Despite the challenges, I thought it would be worth asking for recommendations. Currently, I have a PowerShell script generating a report in ...