Dealing with JSON data retrieved from a Django QuerySet using AJAX

I am utilizing a Django QuerySet as a JSON response within a Django view.

def loadSelectedTemplate(request):
   
    if request.is_ajax and request.method == "GET":
        
        templateID = request.GET.get("templateID", None)
        
        template = list(operationTemplates.objects.filter(templateID = templateID))
        
        if operationTemplates.objects.filter(templateID = templateID).exists():
           
            ser_template = serializers.serialize('json', template )
            return JsonResponse({"valid": True, "template": ser_template}, status=200)
        else:
            
            return JsonResponse({"valid": False}, status = 200)

The JSON response is then captured by JavaScript and can be viewed in the console.

// Perform a GET AJAX request
        $.ajax({
            type: 'GET',
            url: "{% url 'loadSelectedTemplate' %}",
            data: {"templateID": templateID},
            success: function (response) {
                // If valid template, append to textarea
                if (response["valid"]){
                    var template = response["template"];
                    console.log(response);
                }

This is how the JSON object appears in the console log;

{
    "valid": true,
    "template": "[{\"model\": \"opnoteannotator.operationtemplates\", 
        \"pk\": 14, 
        \"fields\": {\"templateCategory\": \"Lower Limb\", 
                     \"templateName\": \"Femoral to below knee Bypass using autologous vein\", 
                     \"templatePreopBundle\": \"WHO check list completed.\\r\\n
                                                Antibiotic Chemoprophylaxis: Co-amoxiclav / Teicoplanin / Gentamicin\", 
                    \"templateIndication\": \"CLTI with night pain / rest pain / tissue loss / infection\", 

I aim to extract the values under "fields" and display them into a text-area on my website. Can someone guide me on how to achieve this? I have attempted various methods, but unable to access the values in JavaScript.

Thank you for your assistance in advance.

Answer №1

Perhaps you could experiment with:

console.log(response['template']);

Answer №2

After realizing that passing the AJAX input from view.py as a JsonResponse was not sufficient, I decided to convert it into a JSON object.

This approach appears to be effective.

 // Sending an AJAX request
        $.ajax({
            type: 'GET',
            url: "{% url 'loadSelectedTemplate' %}",
            data: {"templateID": templateID},
            success: function (response) {
                // If the template is valid, add it to the textarea
                if (response["valid"]){

                    //var template = response["template"];
                    var tem = response.template;

                    // Convert to JSON object
                    var res = JSON.parse(tem);

                    // Empty the text area
                    document.getElementById("opnoteTextArea").value =""

                    // Display in the text area
                    document.getElementById("opnoteTextArea").value += "Template Name: " + res[0].fields.templateName;
                    document.getElementById("opnoteTextArea").value += "\n\nPreopBundle:\n" + res[0].fields.templatePreopBundle;

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

Oops! There seems to be a problem with inserting an image using

I am trying to insert multiple images with a loop when clicked. The images are named "0.jpg","1.jpg","2.jpg" etc. To achieve this, I am using an array with all the elements: {name: '1', result: 1, prefecture: "city", photo1: "0.jpg"}, and my l ...

Having trouble with looping the CSS background using JavaScript in CodePen

Can someone help me with looping through CSS background images? Why is the background not changing in this code example: http://codepen.io/anon/pen/dGKYaJ const bg = $('.background').css('background-image'); let currentBackground = 0; ...

Locate a string containing a series of words separated by a character, with the last word being able to end with any combination of characters through the use of regex

Here are some words to consider: const words = ["apple", "orange", "tomato"] const str = "apple.orange.tomato.$COULD_$_BE_ANY_STRING_HERE" I am in search of a regular expression to verify the format of this string. ...

Building multiple filters on a single related field in Django: A step-by-step guide

Within my Django application, I have a model named Format that contains various fields. Additionally, there is another model called DepartmentFormat structured as follows: class DepartmentFormat(models.Model): department = models.ForeignKey(Department, ...

The issue of Ajax failing to send POST variables to a specified URL

I'm looking to dynamically populate related dropdowns with data fetched from the database. On my HTML page, I have a select element with the id 'fontes' and another one with the id 'cargos'. Below is the jQuery code snippet that I ...

Alternative method to jQuery's "find" selector

$('.wrapper a').filter('a'); //returns all anchors I am trying to find a way to select all anchor elements using a specific selector. The issue is that the find method only looks at descendants, so I need an alternative solution. Any s ...

The signature provided by the pusher is invalid: The expected HMAC SHA256 in hexadecimal digest is

The HTML file contains JavaScript code that calls the server for authentication. The code snippet from the HTML file is as follows: <html> <script> <head> var options = { authEndpoint: "api/pusher.json?socket_id=9900&channel_name ...

What is the method for obtaining a unique id that changes dynamically?

Having trouble accessing the dynamically generated ID in jQuery? It seems to work fine in JavaScript but not in jQuery. Here's an example of the issue: My jQuery code: var img = $("#MAP"+current_img_height); $("#map").css({'height': img.h ...

What is the best way to merge two approaches for tallying items within each category?

I have an Angular 8 application that includes two methods for displaying the number of items in each category. These items are retrieved from the back-end and are categorized as follows: <mat-tab> <ng-template mat-tab-label> ...

Execute Validation Function on Every TextField and Radio Button

I'm new to Javascript and struggling to make my function work for both radio buttons and text fields. Here is the HTML code for the form: <form action="sendmail.php" method="post" name="cascader" onsubmit="prepareEventHandlers()" id="cascader"&g ...

What could be causing the jQuery .load() function to trigger twice?

While using jQuery 1.4 along with jQuery History, I noticed that Firebug/Web Inspector are displaying 2 XHR GET requests on each page load (which doubles when visiting the homepage (/ or /#). For example, if you visit this or any other page with Firebug e ...

Incorporate javascript into your XML transformations with XSLT

I need help with inserting JavaScript in XSLT. Here is an example of what I am trying to do: <xsl:variable name="comboname" select="@name" /> <script type="text/javascript"> var z{$comboname} = {$comboname}; </scri ...

Combining Two Tables Using jQuery

I am currently attempting to combine two tables into one using jQuery in the following manner: var table = document.createElement("table"); table.id = "mergedTable"; $("#mergedTable > tbody:last") .append($("#csvInfoTable2 > tbody").html()) ...

Node js Express js token authentication: unraveling the implementation complexities

After extensive research on authentication methods for nodejs and express js, I find myself at a crossroads. So far, the most helpful tutorial I've found on sessions is this one. I am working with the mean stack and my main goal is to provide users ...

Retrieving JSON formatted data from PHP using jQuery

If I use a $.post method in jQuery, how can I retrieve the response from PHP? $.post("sql/customer_save.php",{ what: "edit",customer_no: $customer_no}); I want PHP to send back a response. echo json_encode(array("customer_id"=>$customer_id,"customer_ ...

Is it possible to prefetch library calls in Next.js in advance?

Recently, I started working with GeoChart using react-google-charts (https://github.com/RakanNimer/react-google-charts). However, I noticed that several scripts load after the entire process is completed. In my scenario, is loading towards the end. Is t ...

Arranging pre-selected checkboxes in MUI Datatable

I noticed that the checked data is appearing at the top of MUI data tables without any sorting. Checkbox In this image you can see that all the checked boxes are mixed up without any order. I would like to have all the checked rows displayed together and ...

Exploring the integration of AJAX and jQuery with Django 1.3

I am completely new to the Django framework, web development, and Python. Currently, I am trying to incorporate AJAX into my project but struggling to find a working sample. I need assistance with integrating AJAX or jQuery within a Django 1.3 project. Cu ...

Navigating to the parent Vue component in a Vue3 project with Composition API structure in WebStorm

After transitioning to Vue3 and embracing the Composition API style, I find myself missing a small convenience that I had when developing in the previous Options API pattern. In WebStorm/IntelliJ IDE, I used to be able to command-click (Mac) on the "export ...

Create and transmit an array of JSON objects

I need help with defining and sending a JSON object array. While I've managed to define a single JSON object, convert it into a string, and send it, I'm stuck on how to do the same for an array of objects. It seems like there might be a simple so ...