skip to Main Content

I’ve built a Django app that submits an AJAX post request to my database. The initial post request works fine, but every previous request is also returned after the first response.

Bottom line: Is there any way to clear the previous AJAX request/responses?

Here’s the first response when I start my server and submit my first request (the request is for pk:1):

MedInput page loaded                                                       (index):46
Med Input Form Submitted                                                   (index):49
csrfmiddlewaretoken=i889gLsqdY9glqI59wRXLTOVehz9Lmp1i5IRikOsgvrGdBD9OpISolDrJ8pqJDmV&input_meds=lisinopril     (index):53
                                                                          (index):60  
[{…}]                                                                     (index):61
    0: {model: "medrec_app.medication", pk: 1, fields: {…}}
    length: 1
    __proto__: Array(0)

This is what happens when I submit another request (this request is for pk:3):


Med Input Form Submitted                                                   (index):49
csrfmiddlewaretoken=i889gLsqdY9glqI59wRXLTOVehz9Lmp1i5IRikOsgvrGdBD9OpISolDrJ8pqJDmV&input_meds=lisinopril     (index):53
                                                                           (index):60  
(2) [{…}, {…}]                                                             (index):61
    0: {model: "medrec_app.medication", pk: 1, fields: {…}}
    1: {model: "medrec_app.medication", pk: 3, fields: {…}}
    length: 2
    __proto__: Array(0)

And here’s what happens when I request pk:1 and pk:3 at the same time:


Med Input Form Submitted                                                   (index):49
csrfmiddlewaretoken=i889gLsqdY9glqI59wRXLTOVehz9Lmp1i5IRikOsgvrGdBD9OpISolDrJ8pqJDmV&input_meds=lisinopril     (index):53
                                                                           (index):60  
    
(4) [{…}, {…}, {…}, {…}]                                                   (index):61 
    0: {model: "medrec_app.medication", pk: 1, fields: {…}}
    1: {model: "medrec_app.medication", pk: 3, fields: {…}}
    2: {model: "medrec_app.medication", pk: 3, fields: {…}}
    3: {model: "medrec_app.medication", pk: 1, fields: {…}}
    length: 4
    __proto__: Array(0)

I only want the responses from the most recent AJAX request/response (which as the last example shows, contains a variable number of models, not just the last one).

I’ve tried setting $.ajax(..., cache: false, ...) which didn’t do anything, and I’ve tried emptying as many dictionaries/lists as I can find.

Is there any way to clear the previous request/responses? What am I missing?

Here’s my code:

views.py

class postMedRec(View):
    form_class = MedInputForm
    template_name = 'medrec_app/med_input.html'
    med_match = []
    med_set = Medication.objects.all()

    def post(self, request):
        if self.request.is_ajax and self.request.method == "POST":
            form = self.form_class(self.request.POST)

            if form.is_valid():

                input_meds = form.cleaned_data['input_meds']
                for med in self.med_set:
                    if re.search(med.generic_name,input_meds, re.IGNORECASE): 
                        self.med_match.append(med)
                ser_meds={}              
                ser_meds = serializers.serialize('json',self.med_match)
                return JsonResponse({'med_output':ser_meds}, status = 200)    
            else:
                return JsonResponse({"error", form.errors}, status= 200)
        return JsonResponse({"error":""}, status=400)

urls.py

app_name="medrec_app"
urlpatterns = [
    path('', MedInputView.as_view(), name="med_input"),
    path('post/ajax/med_rec/', postMedRec.as_view(), name="post_medrec"),
    path('meds/', MedicationList.as_view(), name="med_list"),
    path('meds/<int:pk>/', MedicationDetail.as_view(), name="med_detail"),
    path('meds/add/', AddMedView.as_view(), name="add_med"),
]

med_input.html (my template):

{% extends 'base.html' %}



{% block header %}
<div class="container-fluid">
    <h1 class="display-2">Medication Reconciliation</h1>
</div>
{% endblock header %}

{% block content %}


<div class="container-fluid">
    <form id="med_input_form">
        <div class="form-group" >
            {% csrf_token %}
            <label for="{{form.input_meds.id_for_label}}">{{form.input_meds.label}}</label>
            {{form.input_meds}}
        </div>
        <button type="submit" class="btn btn-primary">Reconcile Meds</button> 
    </form>
</div>

<div class="container-fluid">
    <ul id="med_output">
    </ul>
</div>


<script>
    console.log('MedInput page loaded');
    
    $("#med_input_form").submit(function(event){
        console.log('Med Input Form Submitted');
        event.preventDefault();

        var serializedData = $(this).serialize();
        console.log(serializedData);
        $.ajax({
            type: "POST",
            url: '{% url "medrec_app:post_medrec" %}',
            data: serializedData,
            success: function(response) {
                $('#med_output').html("");
                console.log($('#med_output').html());
                console.log(JSON.parse(response["med_output"]));
                var med_ajax = JSON.parse(response["med_output"]);
                $('#med_output').html('<li>'+med.fields.generic_name+'</li>');              
            }
        })
    });
</script>
{% endblock content %}

{% block javascript %}

{% endblock javascript %}

2

Answers


  1. Chosen as BEST ANSWER

    AANNNNDDD after my last response I realized what I had done wrong. I think I needed my discussion with you to figure it out.

    Originally I had declared med_match = [] outside the POST function, which was causing the issue.

    I added self.med_match = [] INSIDE the POST function, which cleared up the issue I was having.

    So this works perfectly:

    class postMedRec(View):
        form_class = MedInputForm
        template_name = 'medrec_app/med_input.html'
        med_match = []
        med_set = Medication.objects.all()
    
        def post(self, request):
            if self.request.is_ajax and self.request.method == "POST":
                form = self.form_class(self.request.POST)
    
                if form.is_valid():
                    self.med_match = []
                    input_meds = form.cleaned_data['input_meds']
                    for med in self.med_set:
                        if re.search(med.generic_name,input_meds, re.IGNORECASE): 
                            self.med_match.append(med)
                    ser_meds = serializers.serialize('json',self.med_match)
                    return JsonResponse({'med_output':ser_meds}, status = 200)    
                else:
                    return JsonResponse({"error", form.errors}, status= 200)
            return JsonResponse({"error":""}, status=400)
    

    THANK YOU so much for working with me on this!!!


  2. You have set a list as a class variable, causing you to keep appending to it. also why are you using the re module to search?, leave that to the database there is __iexact, __exact, __contains, __icontains, __regex, __iregex and many more available in django when making queries.
    This should work as intended:

    class postMedRec(View):
        form_class = MedInputForm
        template_name = 'medrec_app/med_input.html'
        med_set = Medication.objects.all()
    
        def post(self, request):
            if self.request.is_ajax and self.request.method == "POST":
                form = self.form_class(self.request.POST)
    
                if form.is_valid():
    
                    input_meds = form.cleaned_data['input_meds']
                    med_match = list(self.med_set.filter(generic_name__iregex=input_meds))
                    ser_meds={}              
                    ser_meds = serializers.serialize('json',med_match)
                    return JsonResponse({'med_output':ser_meds}, status = 200)    
                else:
                    return JsonResponse({"error", form.errors}, status= 200)
            return JsonResponse({"error":""}, status=400)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search