Display a Django template in the view following an AJAX post submission

Successfully sending and receiving a JSON object in my views.py file using a POST request (AJAX), but facing difficulty with

return render(request, "pizza/confirmation.html")
. I want the server to perform backend logic on the database and then render a different template for confirmation. However, I am unsure of how to achieve this without utilizing AJAX to transfer a large JSON object. Below is my view:

@login_required
def basket(request):
  if request.method == "POST":
    selection = json.dumps(request.POST)
    print(f"Selection is", selection) # selection appears fine

  context = {"test": "TO DO"}
  return render(request, "pizza/confirmation.html", context) # not functioning  

I have attempted checks for request.is_ajax() and tried using render_to_string for my HTML page, yet it seems that my mistake lies elsewhere. Additionally, I notice in my console that a GET request to my /basket URL occurs after my POST request - unclear why.

Below is my JavaScript code snippet:

    var jsonStr = JSON.stringify(obj); //obj contains my data
    const r = new XMLHttpRequest();
    r.open('POST', '/basket');
    const data = new FormData();
    data.append('selection', jsonStr);
    r.onload = () => {
      // no specified callback needed and limited to using GET here anyway

    };
    r.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    r.send(data);
    return false;

Answer №1

When designing your shopping cart view function, make sure to always render the template as a response. By passing parameters through HttpResponse, you can easily integrate them into your JavaScript snippet. Once the request is complete and you have a response in your JS function, utilize window.location.href to redirect to the desired page. For further insights, refer to this helpful answer.

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

What is an alternative method for passing input value from a parent component to a child in Angular without utilizing ng directives?

Working on an Angular application where I am dealing with communication between parent and child components. I want to send input data to the child component by triggering a click event, and have it displayed upon clicking the submit button. Any suggestio ...

Setting the default tab in easyTabs to be all-powerful

My ajax content is being loaded into a div-container through various navigation links, and I am using the script below to establish the defaultTab: $(document).ready( function() { $("#tab-container").easytabs({updateHash: true, defaultTab: "li:eq(3)"}); ...

Discovering the bound ASP.NET AJAX event handlers for a specific DOM element

I am currently working on customizing a pre-existing ASP.NET 3.5 AJAX web application, specifically SharePoint 2010. Unfortunately, I do not have the ability to modify the source code. My task involves adding a click event handler to act as the first even ...

Save the data retrieved from the success callback of a jQuery.ajax() request to be

Currently in my project, I am attempting to retrieve data from a PHP script. Most AJAX callback functions I have researched show examples where they "use" the data directly in the callback function itself. However, I am looking to fetch data and store it i ...

Regular expressions can be used to extract specific attributes and inner content from a div element within a contentEditable container

Context I am currently developing a tagging system called @Name for my website. Successfully, I have managed to detect names upon keystroke and replace the content with the corresponding div class='tag' data-id='User-id'>Name</di ...

Combining values with identical keys in a PHP MySQL D3 data set

Is there a way to convert data from a MySQL database into a D3 line chart? I have the following data: [{"key":"Branch1","values":["21","1961"]},{"key":"Branch2","values":["21","1961"]},{"key":"Branch2","values":["22","20040"]}] And I want to transform i ...

What is the best way to transform a JSON array in text format into a JSON object array using NodeJS or JavaScript?

I have a RESTful API built with Node.JS and ExpressJS. I want to retrieve a JSON array from the FrontEnd and pass it into my API. api.post('/save_pg13_app_list', function (req, res) { var app_list = { list_object: req.body.li ...

Sending data using AJAX and receiving it in PHP

After spending 3 days and coming across numerous basic questions in this community, I have finally managed to grasp a bit of the concept of ajax post. However, I am still stuck on one little issue - how can I retrieve the value passed by Ajax using PHP? $ ...

Issue with Bootstrap 5 Dropdown not toggling back

<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Creative Admin Panel</title> <link rel="stylesheet" href=&q ...

Stop the page from automatically scrolling to the top when the background changes

Recently, I've been experimenting with multiple div layers that have background images. I figured out a way to change the background image using the following code snippet: $("#button").click(function() { $('#div1').css("background-image ...

Encountering a "Object reference not set to an instance of an object" error when attempting to rebind Telerik Rad

I have implemented two Rad Grid views on a single page. The functionality I am aiming for is that when an item is deleted from the left grid, it should automatically be added to the right grid and vice versa. I have utilized the Rad Ajax Manager for this p ...

Display or Conceal Sub-Header according to Scrolling Position

Question: My goal is to create a specific animation on my website. When loading the page on mobile, I want to display the div with ID "sub-header", but once the user scrolls more than 50px down, I want to hide it. Additionally, if the user scrolls up by 60 ...

Why was the 'Symbol' type introduced in ECMA-262-v6 and what purpose does it serve?

Can you explain the purpose of the 'Symbol' type in ECMA-262-v6? Is it used for fast path implementation for object keys? How does it work internally - does it hash with the assurance that the underlying data remains unchanged? ...

Using an API to fetch a nested array for displaying data in an HTML table

I'm currently developing a program to retrieve and display data from the OpenSky-network API. The API returns an array of airplane information arrays, and I am looking for a way to present this information in an HTML table. Specifically, I want to ext ...

Ways to group and consolidate data based on a shared property?

I am working with a dataset of people, each person having a group attribute assigned to them. The group value is a random string that I do not know in advance when making queries. It is possible for multiple people to have the same group value. My goal is ...

Is there a way to identify a visitor's country and automatically direct them to a relevant website?

Despite reading multiple answers, I am still unsure how to redirect my website's visitors based on their country. I have a basic understanding of HTML and JavaScript. Can someone kindly provide me with the code for this task? ...

Use AJAX to submit the form using the POST method

Struggling with implementing an MVC system. Trying to create a comment system that saves records via POST or AJAX requests. a) Considering separating controllers into Comment_Ajax and Comment_Post. b) Alternatively, using one controller and checking t ...

Is there an alternative, more efficient method to invoke this JavaScript code received through an AJAX request?

I am curious about the use of the eval() function in my code. While it works, I have read that it is not considered best practice to use eval(). I have a scenario where I receive a response from an AJAX call, which is essentially a webpage containing some ...

Is Javascript capable of providing automatic authentication?

Our web application involves accessing a network camera stream, which is secured with a password for the 'root' account. When we try to connect to the camera through the web page, a login prompt appears. We are in need of an automated authentica ...

Error: The Django module 'hello.views' does not have a 'index' attribute when attempting to generate a helloWorld page

I've been attempting to follow the CS Harvard course and I'm currently stuck on lesson three. It seems like they are using Django to create a website, but despite following the instructor's steps exactly, I can't seem to get my other pa ...