What is the best way to send a JavaScript variable to Django using AJAX?

I am facing an issue while trying to pass an array in json format using ajax to my django views. Even though I receive a status of 200 indicating that the POST request has been successfully made, when I attempt to display the data passed in another template, I only see 'None' in console. Any help would be greatly appreciated. The objective is to pass a variable to the views which contains an array of json objects, with the intention of creating a new object for the model in my views. Despite multiple attempts, the code below does not seem to work and returns None.

ajax function:
$.ajax({
    url: 'http://localhost:8000/order-confirmation',
    type: 'POST',
    data: {"array":array},
    processData: false,
    contentType: "application/x-www-form-urlencoded/json",
    dataType: "json",
    headers: {"X-CSRFToken":'{{ csrf_token }}'},
    success: function (result) {
        console.log(result.d);
    },
    error: function (result) {
        console.log(result);
    }
});

urls:
path("order-confirmation", views.order_confirmation, name="confirmation")

views:
@csrf_exempt
def order_confirmation(request):
    array = request.POST.get('array[]')
    context = {
        "arra...

TEMPLATE:

<div class="container">
      <table class="table table-bordered table-dark">
        <tbody>
          {% for row in seats_range %}
          <tr>
     ...

Answer №1

To properly parse JSON in the view, follow this example:

# Import the json library

def order_confirmation(request):
  if request.method == 'POST':
    data = json.loads(request.body)
    print(data['array'])
    # Process the data
    return HttpResponse(status=200) 
  else:
    return render(request, 'main_templates/order_confirmation.html')

Make sure that the variable in AJAX is correctly passed. Check your prints to ensure the view is not causing any issues.
Also, in your template, make sure you are referencing the variable 'array' used in the AJAX call. Replace it appropriately:

{% for row in array %}

After making these adjustments, your code should work as expected and you should see your template in the console.log.

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

Ways to retrieve the ID of the clicked element from the child up to the parent

I currently have a Parent component and a Child component. The Child component contains inner elements called notes, with "delete" being one of them. My goal is to have the Child component return an ID to the Parent component when the delete element is cl ...

The existence of useRef.current is conditional upon its scope, and it may be null in certain

I'm currently working on drawing an image on a canvas using React and Fabric.js. Check out the demo here. In the provided demo, when you click the "Draw image" button, you may notice that the image is not immediately drawn on the canvas as expected. ...

Encountering Angular Material UI issues following the transition from version 11 to 12

I am currently in the process of updating my Angular application from version 11 to 12, integrating Angular Material, and encountering some error messages: Error No.1 - Error NG8002: Cannot bind to 'ngModel' as it is not a recognized property of ...

HashRouter prevents the Framer Motion exit animation from functioning properly

Unfortunately, the exact same question was posted here. Despite no answers provided, I will share my problem as well: Originally, I was using BrowserRouter for routing, but faced issues with refreshing, so I switched to a simple solution using HashRouter ...

Unable to add new tags in Vue multiselect component

Currently, I am utilizing a Vue Multiselect instance with two functions. One function interacts with the database to provide autocomplete functionality, which is working successfully. The second function allows for adding new tags that are not present in t ...

A guide to examining pixels in Three.js

I have a query about comparing two textures at a pixel level in three.js. I am unsure of how to achieve this as the documentation for Three.js does not provide clear answers, with some classes remaining undocumented. In summary, I am looking to determine ...

How to simultaneously update two state array objects in React

Below are the elements in the state array: const [items, setItems] = useState([ { id: 1, completed: true }, { key: 2, complete: true }, { key: 3, complete: true } ]) I want to add a new object and change the ...

"Scotchy McScotchface's to-do list application powered

How is the index.html (frontend Angular) being triggered? The tutorial mentioned that by including one of the following routes in route.js, the frontend gets called app.get('*', function(req, res) { res.sendfile('./public/index.html&ap ...

Using Django URL regex to handle JSON data

I seem to have hit a roadblock in my understanding of json queries. I am attempting to display json data on a view that has the URL structure provided below. http://localhost:8000/structures/hydrants/json?id=%3D2/ This is the regex I am using for the URL ...

Guide on displaying the outcomes of a Haystack Query on a distinct webpage

I have implemented a form in my index.html file: ... {% block searchform%} {% endblock %} ... Within my search/ folder, I have two files. One is search.html, where the form for the index.html is located. {% extends 'index.html' %} {% block s ...

Modify the color of the text input by the user in an AJAX-enhanced text box

After successfully implementing an autocomplete textbox using AJAX Autocomplete, I decided to enhance the feature with some Fuzzy logic. Now, as the user enters 3 characters, my database returns a list of records that match those characters. The search re ...

Exploring the new features of utilizing buttons with the onClick method in the updated nextJS version 14.1.3

"implement customer" import React, { useState } from "react"; import { FaChevronLeft, FaChevronRight } from "react-icons/fa"; export default function HeroSlider() { const images = [ "/images/homepage/home-1.jpeg&qu ...

The Angular Universal error arises due to a ReferenceError which indicates that the MouseEvent is not

I am encountering an error while trying to utilize Angular Universal for server-side rendering with the command npm run build:ssr && npm run serve:ssr. This is being done in Angular8. /home/xyz/projects/my-app/dist/server/main.js:139925 Object(tslib__WEB ...

Converting an HTML form with empty values into JSON using JavaScript and formatting it

While searching for an answer to my question, I noticed that similar questions have been asked before but none provided the solution I need. My situation involves a basic form with a submit button. <form id="myForm" class="vertically-centered"> ...

Is there a way to reset or completely remove the `infiniteajaxscroll` V3 module?

Is there a way to reset or remove Infinite Ajax Scroll on version 3 without using jQuery? I am currently utilizing Import @webcreate/infinite-ajax-scroll. The documentation does not seem to provide instructions for reinitialization or destruction () Infi ...

How can I generate a dummy JSON response using Backbone Fetch?

Exploring Backbone and looking for a way to simulate the response of a .fetch() call within a model without using a testing library or connecting to an external service. If the setting in the model is this.options.mock === true, I'd like to use an in ...

Is axios allowed to be used in this scenario?

As a newcomer to web development, I apologize in advance if my question seems basic or if the details provided are insufficient. Nevertheless, I hope you can assist me with the following query: Is it possible to execute an axios.post request within a vue. ...

Switch up the background picture by chance when hovering over it with the mouse

Would you like to change the background image when hovering over an album, similar to Facebook's functionality? When hovering over an album, display a preview of 3-4 images randomly selected. How can this be achieved using jQuery? I have tried impleme ...

Transferring a row name from PHP to AJAX using jQuery - the complete guide

In my current project, I have a table that displays details fetched from the database. if(mysql_num_rows($sql) > 0) { $row_count_n = 1; while($rows = mysql_fetch_assoc($sql)) { extract($rows); $options1 = select_data_as_options( ...

How to prevent text from overflowing outside the Material UI Container/Box?

One issue I'm facing is with an Alert that displays long strings on my website. Here's the code snippet in question: <Container maxWidth="md"> <Box sx={{ mt: 3, border:1}}> <Box> {hasSubmitted ? ...