A step-by-step guide for efficiently transmitting two JSON arrays via AJAX to be displayed in Django

I am currently implementing ajax to pass a JSON array to the view in Django. On my index page, I have two columns - left and right. Each column contains several text inputs, and there is a 'Save' button that saves all the values from both sides into the database. To achieve this, I created two separate JSON arrays to store the values from each column. However, when I retrieve these arrays in the view.py file, only one of them is received.

Here is an example of my AJAX code and the corresponding code in the view.py file:

var jsonArrLeft = [];
var jsonArrRight = [];

$('#btnSave').on('click', function () {
    $('.form-group.right').each(function () {
        debugger;
        var value = $(this).find("input[name='ValueRight']").val();
        var label = $(this).find("input[name='LabelRight']").val();

        jsonArrRight.push({
            label: label,
            value: value
        });

        var jsonRight = JSON.stringify(jsonArrRight);

        $.ajax({
            url: '{% url 'add_label_value' %}',
            method: 'POST',
            dataType: 'JSON',
            data: {
                'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(),
                'jsonRight': jsonRight 
            },
            success: function (data) {
                alert(data);
            }
        });
    });

     $('.form-group.left').each(function () {
        debugger;
        var value = $(this).find("input[name='ValueLeft']").val();
        var label = $(this).find("input[name='LabelLeft']").val();

        jsonArrLeft.push({
            label: label,
            value: value
        });

        var jsonLeft = JSON.stringify(jsonArrLeft);

        $.ajax({
            url: '{% url 'add_label_value' %}',
            method: 'POST',
            dataType: 'JSON',
            data: {
                'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(),
                'jsonLeft': jsonLeft 
            },
            success: function (data) {
                alert(data);
            }
        });
    });

});

And here is the corresponding code in view.py:

def add_label_value(request):
    if request.method == 'POST':
        try:
            if request.is_ajax():
                order_header = OrderHeader()
                
                jsonRight = json.loads(request.POST.get('jsonRight'))
                
                for x in jsonRight:
                    order_header.label = x.label
                    order_header.value = x.value
                    order_header.position = 'right'
                    order_header.save()

                jsonLeft = json.loads(request.POST.get('jsonLeft'))

                 for y in jsonLeft:
                    order_header.label = y.label
                    order_header.value = y.value
                    order_header.position = 'left'
                    order_header.save()
        
        except OSError as e:
            error = messages.add_message(request, messages.ERROR, e, extra_tags='add_label_value')
            html = '<p>This is not ajax</p>'
            return HttpResponse(html)

Answer №1

In order to improve your code, consider combining both situations into a single AJAX post request and sending it to the view. It seems like you are currently making two separate requests.

    var jsonArrLeft = [];
    var jsonArrRight = [];
    $('#btnSave').on('click', function () {
        $('.form-group right').each(function () {
            debugger;
            value = $(this).find("input[name='ValueRight']").val()
            label = $(this).find("input[name='LabelRight']").val()
            jsonArrRight.push({
                label: label,
                value: value
            })
        $('.form-group left').each(function () {
            value = $(this).find("input[name='ValueLeft']").val()
            label = $(this).find("input[name='LabelLeft']").val()
            jsonArr.push({
              label: label,
              value: value
           })
            var   jsonLeft = JSON.stringify(jsonArrLeft);
            var jsonRight = JSON.stringify(jsonArrRight);
            $.ajax({
                url: '{% url 'add_label_value' %}',
                method: 'POST',
                dataType: 'JSON',
                data: {
                    'csrfmiddlewaretoken':  $('input[name="csrfmiddlewaretoken"]').val(),
                    'jsonRight ': jsonRight ,
                    'jsonLeft': jsonLeft      


},
            success: function (data) {
                alert(data);
            }
        });
    })

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

Error encountered while transitioning to Kubeflow Pipelines version 2 due to JSON decoder issue

Reference: https://github.com/kubeflow/pipelines/issues/7608 I encountered an issue while transitioning a code file from Kubeflow v1 to Kubeflow v2. The code file runs smoothly on Kubeflow v1, but upon moving it to Kubeflow v2, I received the following er ...

PHP script for batch string replacement

My function is triggered by a button click, where it takes two input IDs and forms a string as follows: var str = "headingText=" + $("#headingText").val() + "&centerText=" + $("#centerText").val(); $.ajax({ url: "indexpdf.php", data: str, ...

Find a particular item by referencing a different element

I am attempting to save an element into a string variable, however, in order to locate the desired element I require another element that meets specific conditions. The reason for not directly accessing the intended element is due to the presence of multip ...

Show a single item from the database sequentially and cycle through the rest in a timed loop

I am working on a project that requires displaying specific details on the main screen of my office. The challenge I'm facing is that I need to show only one item at a time and then cycle through each item within a specified time period. Below are th ...

Incorporate HTML code dynamically within a div using jQuery

I need assistance with this code: jQuery('.post-single-content').addClass('padT'); jQuery('.post-single-content').css("padding-top", "40px"); This piece of code essentially changes the following: <div class= ...

What are the steps for populating a table cell with data using AJAX, MySQL, and PHP in the given situation?

The challenge is to create an HTML table with two columns where the first column gets its data from PHP and MySQL. The goal is to turn the values in the first column into clickable links that, when clicked, trigger an AJAX call to fetch information from th ...

Eliminate redundant rows by comparing assorted columns and conditions within Python

In my dataset, I have the following columns. CUI1 CUI2 RELA SL CUI_x SAB_x CODE_x STR_x TTY_x CUI_y SAB_y CODE_y STR_y TTY_y C0010356 C0205721 same_as SNOMEDCT_US C ...

Incorporate a course within the conditional statement

Currently, I'm working on the development of an input site and one of my goals is to highlight empty fields. My plan is to check if a field is empty using an if statement and then apply a specific class that will serve this purpose. This is the JavaS ...

Retrieve a specific div element from the response data in AngularJS

Struggling to extract a specific div element from an AJAX response in Angular? Don't want the entire page content to be displayed? Tried various methods but nothing seems to work. Here's what I have attempted: $http({ method: 'GET&a ...

Adding JQuery Event Handlers to Dynamically Generated Controls

When adding content to my existing div on the page, I encounter an issue where events do not work properly after appending. The text being added contains HTML code within a string. It seems that jQuery only loads controls once on page load, so I may need ...

Tips for specifying a function argument as a subclass of a specific class in Python

Is it possible to specify an argument of a function as an instance of any class, taking into account only the inherited classes that I have specified? Union is similar in concept, but it functions like OR, allowing for instances of A or B or any inherited ...

Is there a way to extract just the JSON data from res?

While creating a search functionality to display a list of users, I encountered an error when attempting to load additional pages to show more users: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data var result = JSON.pars ...

Showcasing the JSON information across separate columns in a unique format

Query regarding organizing data into different columns based on labels. In the provided plunker, data from a JSON file is currently displayed and I need assistance in moving the second iteration to the FEMALE column. Thank you for any help. Plunker URL S ...

Is there a way to programmatically trigger a submit button using jQuery?

In my ScanField, I am scanning a barcode. After scanning, I trim the last four characters of the barcode string and assign it to a hidden field. When I click on the search button, this value is passed to a PHP site via AJAX. For example: if I scan a barco ...

How can you halt a pickle process before it finishes its course?

In my program, I utilize the pickle module to save and load complex datasets, which can sometimes take up to 30 seconds. This process runs in a separate thread and includes a progress dialog with a cancel button. My question is, is it possible to halt the ...

Creating a button that allows updates without refreshing the page can be achieved by implementing

Here are the items I have: <table> <tr> <th> id </th> <th> name </th> <th> update </th> </tr> <tr> ...

Issue with displaying and hiding list elements using jQuery

I am attempting to create an accordion feature using <li> elements with classes .level1, .level2, .level3, and so on. The problem I am encountering is that when I click on a .level2 element, the items hide correctly until the next .level2 element wit ...

Activate DivMenu's second list item automatically

I've been trying to use the trigger function multiple times, but it just won't work. I need help with auto-triggering the menu of the second list element. Can someone please assist me? Here is a snippet of my code: $("document").ready(functio ...

Creating a cutting-edge algorithm for trend detection in Django

Having trouble implementing a simple trending/ranking algorithm in my Django application. My models are Book and Reader. New books are added to the database every night, along with updated reader statistics for each book (one record per day). Looking to ...

Utilize AJAX and JavaScript to retrieve file information and facilitate file downloads

I have developed a script that intercepts Captcha form submissions. Typically, when the form is submitted, a file will be downloaded (such as exe or zip) in the usual way where it appears at the bottom of the Chrome browser and gets stored in the "download ...