Flask is failing to display AJAX data

Looking to embark on a Flask project involving sending an AJAX request. In the Flask code, I want to assign a variable to handle the request and display it on the page using a Jinja variable.

Flask

from flask import Flask,render_template,request
app = Flask(__name__)
@app.route("/a",methods=['POST','GET'])
def home():
    a = None
    if request.method == 'POST':
        a = request.form['data']
        print(a)
    return render_template('new5.html',p=a)
if __name__ == '__main__':
    app.run(debug=True)     

HTML

<!DOCTYPE html>
<html>
    <body>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script>
            var place = 'asd'
            $.ajax({
                url: '/a',
                type:'POST',
                data : {'data':place}    
            })
        </script>
        <p>{{p}}</p>
    </body>
</html>

Encountering issues as the output of a in the console shows 'asd' even though that's not what I expect. Could use some guidance on how to rectify this.

Appreciate any help!

Answer №1

It appears there may be some confusion regarding the concept of AJAX. Simply put, AJAX involves using JavaScript to manipulate the content of a loaded webpage.

For instance, on platforms like StackOverflow, AJAX is utilized to alert users when a question has been edited -- a notification card pops up to inform you of the change, allowing you to refresh that specific portion of the page. Without AJAX, users would need to manually refresh the entire page to check for updates, resulting in increased server load and internet usage.

With AJAX, rather than loading the entire page to check for changes, targeted requests can be made to the server for specific information (e.g., "Has this page been edited?"). This communication is facilitated through an API, which outlines how different systems can interact with each other.

An API serves as the interface connecting two components: the frontend (the user's browser running JavaScript) and the backend (the server-side code). In web development scenarios, the frontend is typically written in JavaScript, while frameworks like Flask allow developers to build the backend using Python.

As an example, consider a basic timer application I have created. Upon loading the page, the initial HTML displays the current timer value from the server. However, since the timer constantly changes, the JavaScript code queries the server regularly for the updated time. Clicking the button instructs the server to reset the timer, prompting the countdown to restart during the next update.

Python:

from flask import Flask, render_template, jsonify, request
import time

app = Flask(__name__)

timer_reset_at = time.time()

def get_time():
    """Calculates the duration since last reset, in seconds"""
    return time.time() - timer_reset_at


@app.route('/api/time', methods=['GET', 'DELETE'])
def time_api():
    """
    Handles GET: returns time elapsed since last reset.
    Handles DELETE: resets the timer.
    """

    if request.method == 'DELETE':
        global timer_reset_at
        timer_reset_at = time.time()
        return jsonify([])
    return jsonify({'time': get_time()})

@app.route('/')
def index():
    return render_template("index.html", time=get_time())

if __name__ == '__main__':
    app.run('0.0.0.0', 5000)

HTML:

<!DOCTYPE html>
<html>
    <body>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        
    <h1>Timer app!</h1>
    <p>Time since last timer reset: <span id="time" style="color: red;">{{time}}</span></p>
    <button onclick="reset(); return false;">Reset timer!</button>

        <script>
        function reset() {
            $.ajax({
          url: "{{url_for('time_api')}}",
          type: 'DELETE'
        });
        }
            setInterval(function() {
            $.ajax({'url': "{{url_for('time_api')}}", success: function(result){
                $('#time').html(result.time);
        }});
      }, 100);
    </script>
    </body>
</html>

If @Detlef's suggestion in the comments is accurate and your goal is to collect user input, process it, and display it on another page, then AJAX may not be necessary. An alternative technology that has been around since the beginning is the use of forms.

You previously attempted to utilize request.form in your code sample. This method works well when dealing with form-encoded POST data, a task that forms handle automatically. Below is an example illustrating an app where users can view recently submitted comments and add new ones using a simple form setup.

Python:

from flask import Flask, render_template, request

app = Flask(__name__)

def get_comments():
    try:
        with open("comments.txt") as file:
            return file.read()
    except FileNotFoundError:
        return None

def append_comment(new_comment):
    with open("comments.txt", "a") as file:
        print('---', file=file)
        print(new_comment, file=file)

@app.route('/', methods=['GET', 'POST'])
def index():
    """
    If GET, display the index page with existing comments.
    If POST, add the submitted comment to the list before displaying the updated page.
    """
    did_add_comment = False
    if request.method == 'POST':
        did_add_comment = True
        append_comment(request.form['comment'])
    return render_template('index.html', comments=get_comments() or "No comments yet, try adding some!", comment_added=did_add_comment)

if __name__ == '__main__':
    app.run('0.0.0.0', 5000)

HTML:

 <!DOCTYPE html>
<html>
    <body>
      <h1>Comments app!</h1>
      {% if comment_added %}
        <p style="color: red;">Your comment has been added!</p>
      {% endif %}

      <p>Latest comments:</p>
      <pre>{{comments}}</pre>
      <hr>
      <form method="POST">
        <label for="comment">Add your own comment:</label>
        <textarea id="comment" name="comment"></textarea>
        <input type="submit" name="Add comment!">
      </form>
    </body>
</html>

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, looks like the server is experiencing some technical difficulties. The request is taking too long to process and has timed out

I find myself in a predicament with my shared hosting. Despite modifying my ajax requests to be smaller and adding timeouts after each request, the issue persists. How can I resolve this problem while using shared hosting? Note: set_time_limit(0); is not p ...

Executing a method to retrieve a value from an empty function in Node.js

I am currently dealing with the code snippet below: function done(err, file) { //handling of code here return "test"; } function process() { retext() .use(keywords) .process(sentence, done); return val; } The proce ...

Is there a lone wanderer in the Ajax reply?

Currently working on a Wordpress project, I encountered an issue with my Ajax call. Upon making the call using jQuery, PHP returns a JSON object. However, the JavaScript response includes an unexpected "0" at the end, causing the decoding of the JSON objec ...

What is the best way to have the sidebar of a webpage slide out over the main body content that is being displayed?

Issue Summary I am experiencing an issue with the positioning of my sidebar, which is initially located 66% offscreen using -translate-x-2/3. The sidebar is meant to be pulled into view onmouseover, however, the main body content remains stuck in place. I ...

In vue, pagination links are displayed as dots instead of numbers

Struggling to integrate pagination in vue. Facing an issue where the pagination links are appearing as dots, depicted in the attached image. The correct number of pagination links display and I can navigate through different pages using the side navigation ...

The configuration for CKEditor5's placeholder feature seems to be malfunctioning

I am currently experimenting with a customized version of CKEditor 5 known as BalloonBlockEditor. Below is the custom build output that I have created: /** * @license Copyright (c) 2014-2023, CKSource Holding sp. z o.o. All rights reserved. * For licens ...

When using the Infinite Scroll React component, only a single new set of objects is loaded as you scroll down, and the loading

My React component is designed to load 6 images at a time as the page is scrolled down, creating an infinite scroll effect similar to what YouTube and Reddit now use. Currently, when the page loads, it shows the initial 6 images correctly. However, as I c ...

Idle Time in Nextjs - Making the Most of D

I've been experiencing a significant delay of around 6 seconds when refreshing my Next.js platform. As part of my debugging process to identify the root cause of this issue, I uncovered that approximately 5 seconds of this time is classified as idle. ...

Issue with deep linking functionality on S3 storage service turning out to be

After successfully deploying my angular5 app to: http://myApp.s3domain.amazonaws.com The Angular router is automatically directing me to http://myApp.s3domain.amazonaws.com/home However, when I try to access a link with a unique parameter like so: http:/ ...

Personalized style for text overflow property

The application is created using Angular. Within a component, we have a div containing some text: <div>abcdefghijklmnop<div> Depending on the screen size, the text should either be fully displayed or clipped. I discovered the property 'te ...

Inserting data into a table using variables in Mssql database management system

I'm really struggling to find a way to safely add my Variables into an MSSQL server. I've tried everything. Could someone please help me and provide the solution for adding my Variables into the Database? It is crucial that I prevent any possib ...

What are the steps to ensure compatibility with relative paths when transitioning from v5 to v6?

In my application, there are scenarios where multiple routes must pass through a component before rendering specifics. Additionally, there are situations where something is displayed for the parent route and then divided for the children. It's crucia ...

Unknown and void

undefined === null => false undefined == null => true I pondered the logic behind undefined == null and realized only one scenario: if(document.getElementById() == null) .... Are there any other reasons why (undefined === null) ...

Utilizing PHP Variables in Ajax Calls: Transferring Data between JS and PHP

I've been struggling to grasp how to pass information from PHP to JavaScript and vice versa. I've spent an entire night trying to figure this out and would really appreciate it if someone could help me understand how to send two variables to an a ...

Having trouble with uploading images using Form.File in React?

I'm facing an issue with my React code for uploading an image. It doesn't seem to be working and I can't figure out why. Can someone please assist me? return ( <div> <FormContainer> <h1>Edit Product& ...

Revamping this snippet - JavaScript with NodeJs

Currently working on a basic CRUD application, encountering an issue with obtaining the auto-incrementing value for the latest account in MongoDB. To provide more context, I've included the snippet below to achieve the following: 1) Conduct validati ...

Manipulating a 2D array in Javascript and Jquery: Implementing push functionality

I am trying to set up an array structure as follows: track[divID][wrapID] However, when I attempted track[divID][wrapID] = wrapID, I encountered an issue. This is because I need to add more elements to the second dimension in another loop, like this: tr ...

Troubleshooting: React is not defined in Rollup + React 17 with updated JSX Transform

I'm currently working on prototyping a microfrontend architecture using Rollup and multiple create-react-app applications. However, when I try to locally yarn link my external app with the container app, I am encountering the following error: The err ...

Choosing Between Methods and Computed Properties in Vue.js

Can you explain the primary distinction between a method and a computed property in Vue.js? I'm finding it tricky to differentiate between the two as they appear quite similar. ...

Validator returns undefined when expressing invalid data

Having an issue with validation, here is the code snippet: routes.js var express = require('express'); var router = express.Router(); var hello_controller = require('../api/controllers/helloController'); var { validationRules, validat ...