Update a form using jQuery/AJAX

Hi.

Let me summarise my workflow as follows:

  • User requests a modal
  • User selects from a drop-down menu in this modal
  • JavaScript submits an AJAX request (onchange)
  • Server returns a JSON Response (using Django)
  • JavaScript updates input fields on the page from that response

The last point causes trouble. I get the server response, but the value of the form does not change.

Here you can see the Ajax-Request:

$.ajax({
		type: "POST",
		url: "/en/asset/get_param_suggestion/",
		data: JSON.stringify(server_data),
		contentType: "application/json",
		dataType: 'json',
		success: function(response) {
			alert("Got response from server ...", response);
			alert(response['form_html']);
			$('#act_ids_form_div').html(response);
			}
	});

This is the orginal HTML form.

asset_create_form.html (section)

<div class="form-group{% if field.errors %} invalid{% endif %}">
                {{ field|as_crispy_field }}
					{% if form.asset_type_name == "myPredefinedSource" %}
						<!-- div to update the part of the form that must be updated -->
						<div id="act_ids_form_div">{% include "asset/asset_create_form_param_suggestion.html" %}</div>
					{% endif %}
</div>

And this is the part of the form that should be updated.

asset_create_form_param_suggestion.html

{% load crispy_forms_tags %}
<!-- put here everything that must be updated on the change of your drop down list -->
<div class="row-fluid">{{ form_suggestion.non_field_errors }}</div>
{% for field in form_suggestion %}
     <div class="form-group{% if field.errors %} invalid{% endif %}">
	 {{ field|as_crispy_field }}
	 </div>
{% endfor %}

in Python (Django):

@login_required
@require_http_methods(["POST", "GET"])
def get_inputparameter_suggestion(request):
    # response_dic={}
    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)
    print(body)    
    form_suggestion = SuggestionForm(initial={"capex": 600000})    
    
    form_html = get_template("asset/asset_create_form_param_suggestion.html")
    return JsonResponse(
        {"success": True, "form_html": form_html.render({"form_suggestion": form_suggestion})}, 
        status=200
    )

Thank You!

Take a look at what you alert and what you put in the html. Then you should find your issue…

<!-- put here everything that must be updated on the change of your drop down list -->
<div class="row-fluid"></div>
<div class="form-group">
<div id="div_id_capex" class="form-group">
<label for="id_capex" class="">
Capex
</label>
<div>
<input type="number" name="capex" value="600000" 
placeholder="e.g. 4000" min="0.0" step=".01" data-bs-toggle="tooltip" 
title="Actual CAPEX of the asset, i.e., specific investment costs." style="font-weight:400; 
font-size:13px;" class="numberinput form-control" id="id_capex">
</div>
</div>
</div>

The wanted value is actually in the html . . .