Home » Jquery » jquery – Django dynamic table using AJAX

jquery – Django dynamic table using AJAX

Posted by: admin February 22, 2020 Leave a comment

Questions:

I want to dynamically load the table to my html page after ajax form submit. Below is my view definition

def patients_create(request):
    data = dict()
    if request.method == 'POST':
        form = PatientForm(request.POST or None)
        if form.is_valid():
            form.save()
            data['form_is_valid'] = True
            patient_list = Patients.objects.all()
            data['html_patient_list'] = render_to_string('dental/patients_list.html',
                                                         {'patients': patient_list})
        else:
            data['form_is_valid'] = False
    else:
        form = PatientForm()
    context = {'form': form}
    return render(request, 'dental/partial_patient_create.html', context)

and ajax js script

$(function () {
$("#modal-book").on("submit", ".js-book-create-form", function () {
    var form = $(this);
    $.ajax({
      url: '/partial_patient_create',
      data: form.serialize(),
      type: form.attr("method"),
      dataType: 'html',
      success: function (data) {

          alert("Book created!");  // <-- This is just a placeholder for now for testing
          $("#patients tbody").html(data.html_patient_list);
          $("#modal-book").modal("hide");
      }
    });
    return false;
  });
});

the problem is with this part of code $("#patients tbody").html(data.html_patient_list);. In java script file it is marked as unresolved variable. How can I pass the variable from views.py file to JavaScript file?

Thanks in advance

How to&Answer: