How to display the values of the attributes of the data queried and retrieved by Ajax call in django

Viewed 42

I am trying to query the database based on what the user has clicked on the page and display the data retrieved by it without refreshing the page. I am using Ajax for this. Let me show you the codes

html

<label for="landacq" class="civil-label">Land Acquisation Cases</label>
<input class="civil-category" type="radio" name="civil-cat" id="landacq" value="land acquisation" hidden>

<label for="sc" class="civil-label">Supreme Court</label>
<input class="civil-court" type="radio" name="civil-court" id="sc" value="supreme court" hidden>

<label for="limitation" class="civil-label">Limitation</label>
<input class="civil-law-type" type="radio" name="civil-law-type" id="limitation" value="limitation" hidden>

js


for (i = 0; i < lawTypeInput.length; i++) {
  lawTypeInput[i].addEventListener("click", (e) => {
    e.preventDefault();
    cat = civilCatval;
    court = civilCourtval;
    lawT = civillawTypeval;
    console.log("this is from ajax : ", cat, court, lawT);
    $.ajax({
      type: "POST",
      headers: { "X-CSRFToken": csrftoken },
      mode: "same-origin", // Do not send CSRF token to another domain.
      url: "civil",
      data: {
        "cat[]": civilCatval,
        "court[]": civilCourtval,
        "lawT[]": civillawTypeval,
      },
      success: function (query) {
        showCivilQ(query);
        // console.log(data);
      },
      error: function (error) {
        console.log(error);
      },
    });
  });
}

function showCivilQ(query) {
  q.textContent = query;
  console.log(query);
}

So here for example, if the user the click the radio button in the html, the values are grabbed by in js file and then sent to the url mentioned as a POST request. There these values are use to filter the database and return the objects like this

views.py

def civil_home(request):
    
    if request.is_ajax():
    
      get_cat = request.POST.get('cat[]')
      get_court = request.POST.get('court[]')
      get_lawT = request.POST.get('lawT[]')

      query = Citation.objects.filter(law_type__contains ='civil' ,sub_law_type__contains= get_cat, court_name__contains = get_court, law_category__contains = get_lawT)

      return HttpResponse(query)
    else:
      subuser = request.user

      subscription = UserSubscription.objects.filter(user = subuser, is_active = True)

      context = {
        'usersub': subscription,
      }
    

      return render(request, 'civil/civil_home.html', context)

This is the result I am getting which is correct.

result of what I am getting

My Question is these objects contain attributes having some values in for eg, title, headnote etc. How can I display these attributes in the html rather than displaying the object names returned as shown in the Image like title of the citation, headnote of the citation etc

2 Answers

A solution could be to return a json object instead of the query resultset; because Ajax works well with json

You need a function that translates a Citation object into a dictionary (change it based on your real attributes). All elements must be translated into strings (see date example)

def citation_as_dict(item):
    return {
        "attribute1": item.attribute1,
        "attribute2": item.attribute2,
        "date1":  item.date.strftime('%d/%m/%Y')
    }

This dictionary must be translated into a json through import json package

def civil_home(request):
    
    if request.is_ajax():
    
      get_cat = request.POST.get('cat[]')
      get_court = request.POST.get('court[]')
      get_lawT = request.POST.get('lawT[]')

      query = Citation.objects.filter(law_type__contains ='civil' ,sub_law_type__contains= get_cat, court_name__contains = get_court, law_category__contains = get_lawT)

      response_dict = [citation_as_dict(obj) for obj in query]
      response_json = json.dumps({"data": response_dict})
      return HttpResponse(response_json, content_type='application/json')

    else:
      subuser = request.user

      subscription = UserSubscription.objects.filter(user = subuser, is_active = True)

      context = {
        'usersub': subscription,
      }
    

      return render(request, 'civil/civil_home.html', context)

In your HTML page you should be able to parse the response as a normal JSON object

I figured out another way to do it, which is giving me the required results too.

Here I am filtering the values of the query, and then converting it to a list and passing it as a JsonResponse views.py

def civil_home(request):
    
    if request.method == "POST" and request.is_ajax():
    
      get_cat = request.POST.get('cat[]')
      get_court = request.POST.get('court[]')
      get_lawT = request.POST.get('lawT[]')

      query = Citation.objects.values().filter(law_type__contains ='civil' ,sub_law_type__contains= get_cat, court_name__contains = get_court, law_category__contains = get_lawT)

      result = list(query)

      return JsonResponse({"status": "success", "result": result})
    
    else:
      subuser = request.user

      subscription = UserSubscription.objects.filter(user = subuser, is_active = True)

      context = {
        'usersub': subscription,
      }
    

      return render(request, 'civil/civil_home.html', context)

And then I am recieving the reponse here and iterrating over it to print the attributes in the html js


for (i = 0; i < lawTypeInput.length; i++) {
  lawTypeInput[i].addEventListener("click", (e) => {
    e.preventDefault();
    cat = civilCatval;
    court = civilCourtval;
    lawT = civillawTypeval;
    console.log("this is from ajax : ", cat, court, lawT);
    $.ajax({
      type: "POST",
      headers: { "X-CSRFToken": csrftoken },
      mode: "same-origin", // Do not send CSRF token to another domain.
      url: "civil",
      data: {
        "cat[]": civilCatval,
        "court[]": civilCourtval,
        "lawT[]": civillawTypeval,
      },
      success: function (response) {
        console.log(response.result);
        civilData = response.result;
        if ((response.status = "success")) {
          $("#queryResult").empty();
          for (i = 0; i < civilData.length; i++) {
            $("#queryResult").append(
              `
              <a href="">${civilData[i].title}</a>
              <p>${civilData[i].headnote}</p>
            `
            );
          }
        } else {
          $("#queryResult").empty();
          $("#queryResult").append(
            `
              <p>No Citations Found</p>
            `
          );
        }
      },
      error: function (error) {
        console.log(error);
      },
    });
  });
}

A csrf_token can be mentioned at the top of the html page and then it can be passed in the header to avoid any conflict.

Related