Using AJAX to retrieve Django view return values

I am currently using Django along with AJAX,

Within my template, users have the ability to select an option and then submit their choice. Upon clicking the submit button, an Ajax function is triggered which sends the data to my view for processing, and then should return a value back to the template.

The problem arises when the POST request reaches the view - nothing is being returned to the template. It's unclear whether this is due to the view not receiving any data or if it's failing to trigger any conditional statements. The process seems to be functioning correctly but no results are being displayed.

This is how my HTML form looks:

<form method="POST" id="buy_form" name="buy_form" action="{% url 'manage:buy' %}">
    {% csrf_token %}
    <div class="buy_top_section">
        <div class="width">
            <div class="spacing">
                <h3 class="sell_title">How much do you want to sell?</h3>
                <input type="text" id="amount" class="buy_input_top" maxlength="10" name="amount" type="number" required>
                <select id="selected" class="buy_selection" name="wanted">
                    <option value="generate_b">BTC</option>
                    <option value="generate_e">ETH</option>
                    <option value="generate_l">LTC</option>
                </select>
            </div>
            <span class="float_clear"></span>
            <button id='generate' type="submit" value="currency_details" class="custom_button"l">Generate
            </button>
        </div>
    </div>
</form>

<!-- The expected output from the view -->
<h1>{{ address }}</h1>

My AJAX code snippet: $(document).on('submit', '#buy_form', function (e) { e.preventDefault()

    $.ajax({
        type: 'POST',
        url:'/manage/buy/',
        data:{
            currency:$('selected').val(),
            amount:$('#amount').val(),
            csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
            },
            success: function (){

            }
        })
    });

My Django View implementation:

def buy_corsair(request):

    if request.method == 'POST':

    if request.POST.get('wanted') == 'generate_b':
        # Retrieving the entered amount
        amount = request.POST.get('amount')
        # Generating a new B address
        new_b_address = client.create_address(b_account_id)['address']
        # Associating the address with the user
        request.user.user_address.b_address = new_b_address
        # Saving the address for the current user
        request.user.user_address.save()
        # Passing on the address to the template
        context = {'address': new_b_address}
        return render(request, context)

urls.py configuration:

urlpatterns = [
    # Buy Page
    path('buy/', views.buy_corsair, name='buy'),
]

Answer №1

When making Ajax requests, they run in the background and Django's render function renders a template to the body, so you cannot render this way. You could do it like this;

Don't forget to include

from django.http import HttpResponse

def buy_corsair(request):
    if request.method == 'POST':    
        if request.POST.get('wanted') == 'generate_b':
            # Get the amount entered
            amount = request.POST.get('amount')
            # Generate a new B address
            new_b_address = client.create_address(b_account_id)['address']
            # Point the address at the user
            request.user.user_address.b_address = new_b_address
            # Save address to current user
            request.user.user_address.save()
            # Pass the address to the template
            return HttpResponse(new_b_address)

In your JavaScript file;

$.ajax({
    type: 'POST',
    url:'/manage/buy/',
    data:{
        currency:$('selected').val(),
        amount:$('#amount').val(),
        'csrfmiddlewaretoken': "{{ csrf_token }}"
        },
        success: function (data){
            $('h1').html(data);
        }
    })
});

Answer №2

within your Django controller

import json
from django.http import HttpResponse
def purchase_msi(request):
   if request.method == 'POST':
      if request.POST.get('desired') == 'create_m':
         # Retrieve the entered amount
         quantity = request.POST.get('quantity')
         # Generate a new M address
         new_m_address = client.create_address(m_account_id)['address']
         # Link the address to the user
         request.user.user_wallet.m_address = new_m_address
         # Save address for current user
         request.user.user_wallet.save()
         # Provide the address to the template
         context = {'address': new_m_address}
         return HttpResponse(json.dumps(context))

within your javascript file

 $.ajax({
    type: 'POST',
    url:'/manage/purchase/',
    data:{
        currency:$('chosen').val(),
        quantity:$('#quantity').val(),
        csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
        },
        success: function (response){
            console.log(response);
            //retrieve the value and display it in the console//
            var obj=JSON.parse(response)["address"];

            alert(obj);
      
        }
    })
});

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 the best way to convert integer values in pandas from having a "," for thousands to just a regular integer without ","?

I have a large dataframe with integers and floats inside. Some of the values exceed one thousand, which causes errors when trying to use them as integers. For example: A B C 0 1,598 65.79 79 1 -300 46.90 ...

Safari is unable to establish a connection with the local URL: http://127.0.0.1:5000

I am attempting to execute this Flask code for a simple "hello world" application: app = Flask(__name__) @app.route("/") def hello_world(): return "<p>Hello, World!</p>" However, Safari is refusing to connect to the URL ...

Hiding widgets using self.grid() in Tkinter

While creating a username/password confirmation using the tkinter library, I encountered an issue where the widgets are no longer displayed. """ Password entry/confirmation class """ from tkinter import * class Menu: def __init__(self,master): ...

The select option fails to automatically assign the selected value from a given response

I am currently working on a project that involves populating two select dropdowns with values from a server. While I am able to successfully retrieve and populate the options of the first select dropdown, I am encountering an issue with setting one of the ...

Locating an element in a table using the index number with XPath

Seeking an element's location in Python Selenium by its index number. This is the xpath for the specific element: /html/body/div[4]/div[1]/div[3]/div/div[2]/div/div/div/div/div/div/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div/div[3]/div[1] ...

Dropdown menu utilizing processing API and interacting with AJAX and DOM manipulation

My API data is not showing up in the dropdown menu. If I use ?act=showprovince, I can see the result. example.html <head> <link rel="stylesheet" type="text/css" href="css/normalize.css"> <link rel="stylesheet" type="text/css" hr ...

Access the contents of a text file using encoding= cp1256 for optimal reading

Attempting to extract data from a file encoded with cp1256 has been causing some issues for me. While I am able to read the file and display its contents without any problems, using line.startswith to search for specific information does not seem to be fun ...

Unleash the power of AJAX to dynamically load additional content on

I am in need of a straightforward method to incorporate a "load more" button into my JSON results. Here's the relevant snippet of code: // GETTING JSON DATA FOR TIMELINE $UserTimeline = 'MYSITE/TimelineQuery.php?id='.$UserPageIDNum.'&a ...

Sending values from multiple radio groups in JavaScript can be done by accessing each group individually and extracting

This is an add to cart system. Currently, I am able to send quantity with an ID. However, I also want to send radio group values. How can I achieve this? Here are my codes: product.php <script> jQuery(function ($) { $('.popbutton').on(&a ...

Python - Merge two lists of dictionaries by checking for a specific key, and filter out any entries that do not meet the criteria

Is there a way to merge two lists of dictionaries where one field is contained within another field, and only include matches? list_1 = [{ "bytes_in": 0, "rsrq": -50, "hostname": "AB9472" }, { "bytes_in": 0, "rsrq": -90, "hostname" ...

jquery accordion not functioning properly following partial ajax page refresh

Initially, I'm using a jQuery accordion that works perfectly. However, I encounter an issue when implementing some Ajax commands to reload part of the page, specifically the inner body section. After the page reloads, the accordion breaks because the ...

What are the steps to validate an Ajax form using Dojo JavaScript?

Currently, I am in the process of validating a form that has been written in Javascript/Dojo before sending it via Ajax. Here is the code snippet: <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js" type="text/javascript" djConf ...

Django: A guide to efficiently retrieving related objects along with a model instance

ClassOne: ... ClassTwo: ForeignKey(One) ClassThree: ForeignKey(Two) Currently, I have an object of Three. t = Three() two = t.two one = two.one During this process, the database needs to be accessed three times. Is there a way to fetch all ...

Creating a mouse locator program in Python: A step-by-step guide to developing a tool similar to the Free Utility for tracking mouse cursor position

Looking to create a mouse locator program using Python? (similar to the Free Utility that locates mouse cursor position) I need help displaying the coordinates in the window as the mouse moves. import tkinter as tk import pyautogui as pag win = tk.Tk() ...

Condense Python Dictionary to Boolean Values

Imagine having a Python dictionary with nested dictionaries to any level and a mix of keys representing boolean choices and others that don't. For example: {'Key1': 'none', 'Key2': {'Key2a': True, 'Key2b& ...

Embed a hyperlink within an informational passage

I have a search box with Ajax functionality like this; And I want to customize the NotfindText message to display as: "No results found, but you can try advanced search from here" However, I am struggling to add the link. I do not have much knowledge abo ...

Converting for loop to extract values from a data frame using various lists

In the scenario where I have two lists, list1 and list2, along with a single data frame called df1, I am applying filters to append certain from_account values to an empty list p. Some sample values of list1 are: [128195, 101643, 143865, 59455, 108778, 66 ...

Python code to transform a dictionary into binary format

I have a unique system where customer IDs are linked with movie IDs in a dictionary. Even if the customer watches the same movie multiple times, I want to simplify it as a single entry. In order to achieve this, I need to convert my dictionary data into bi ...

Tips for storing data from a table using a button

I have implemented a data table to display information from a database. I am looking for a way to save user information whenever they export data in Excel, CSV, or PDF format from the table. I have already created a function to handle saving user data, but ...

The issue of Jquery not functioning properly within Ajax-included HTML documents

I've tried looking at some other posts, but I couldn't understand them. The jQuery works fine when the page is loaded, but when the same elements are loaded from an AJAX script, the jQuery doesn't work. I know I need to do a callback, but ca ...