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

Struggles with ajax and JavaScript arise when attempting to tally up grades

Currently, I am facing an issue with my JavaScript. The problem arises when trying to calculate marks for each correctly chosen answer based on information from the database. If an incorrect answer is selected, the marks are set to '0', otherwise ...

Knockout Observable Array causing UI to freeze and not refresh properly

I recently started using knockout and am exploring the use of observable arrays to track changes from the UI. The initial data is loaded into the array and I'm attempting to dynamically add new objects to the array from another screen. Although I hav ...

JavaScript slowness

Currently, I am developing a test page that consists of buttons triggering various scripts. One of the functionalities I am trying to implement is changing the background color every second for 5 seconds, cycling through a total of 5 different colors. Desp ...

Using angularjs, populate a dropdown menu by enclosing the options in curly braces

Utilizing the curly braces syntax interpolation in AngularJS allows us to connect data from the model to the view. This technique is typically used for displaying text. Is there a way to populate a dropdown list using the {{}} syntax? ...

Analyzing the number of rows by utilizing variables stored in an array

Greetings everyone! I am currently attempting to compare the number of rows returned by two queries, for which the values are fetched from an array within a while loop. Below is the PHP code snippet: $get_section = "SELECT * FROM s ...

Creating dynamic web content using KaTeX and Node.js

When I attempt to display a complex formula using HTML and CSS, I encounter difficulties. Instead of the desired output, my screen is filled with confusing unicode characters. To resolve this issue, I decided to use KaTeX. I downloaded KaTeX into the dire ...

Is there a way to modify the props.data in a child component?

I need assistance with displaying a range from an array that is passed into a child component. Currently, my Parent component looks like this: import data from './data.json' return ( <Cell symbol={data.symbol} number={data.number} /> ) ...

How can I remove the focus highlight from the MUI DatePicker while retaining it for the TextField?

I am currently working on developing a date picker using react.js with the MUI DatePicker library. The code I have implemented closely resembles what is provided in their documentation. However, upon rendering the component, I am encountering an issue whe ...

Encountering a TypeError with DataTables and Tabledit

I've been attempting to integrate DataTables with Tabledit, but I keep encountering the error message "TypeError: Cannot set properties of undefined (setting 'nTf')". The number of tags also matches up. Interestingly, if I comment out the " ...

JavaScript recursive reduce function

Looking to filter through an Array of objects and extract only those with the key is_enabled=true from another Array of objects. Structure of the data: [ { 'id': 1, 'label': 'Label1', 'option ...

PHP echo functions are not functioning properly in a dynamically loaded PHP page through jQuery's .load function

Within my WordPress installation, I have index.php and desktop.php files. The goal is to load desktop.php into #tLoad only if the browser window width is greater than 800px. While this works fine, I am encountering issues when trying to use PHP functions a ...

What is the best approach to send data to the parent when closing $mdDialog?

When I open a Dialog Window, it has its own controller. Is there a way for me to modify data in the differentController that belongs to the Dialog Window and then send the modified data back to the parent controller when the dialog is being removed? fun ...

Checking the URL in Redux Form

I am currently using the redux-form library to manage my form in React Redux. I have successfully implemented validation for fields like email and name. However, I am facing an issue with validating a URL field in redux-form. What specific format should I ...

retrieve the current image source URL using JavaScript

In the template below, I am looking to extract the current img src URL and utilize it in a fancybox button. For example, in the template provided, there are 3 images from https://farm6.staticflickr.com. When clicking on these images, the fancybox will ope ...

Extract latitude and longitude data using Mapbox's autocomplete feature

Currently, I have integrated Mapbox with autocomplete in a Vue component: <template> <div> <div id='geocoder'></div> </div> </template> <script> import mapboxgl from 'mapbox-gl& ...

Position the typography component to the right side

Is there a way to align two typography components on the same line, with one aligned to the left and the other to the right? I'm currently using this code but the components are aligned next to each other on the left side. const customStyles = makeSt ...

Obtain user input from a form and assign it to a variable in a jQuery AJAX

How can I pass the value of an HTML Input Form to a jQuery AJAX call's URL as `amt` in `url: "http://localhost:8080/orderNo?amount=" + amt,`? The input value logs to the console when calling getAmtValue(), but I'm struggling to access the `amt` ...

Exploring the world of tweets using React

While trying to retrieve tweets using the Twit package, I keep encountering error 400. I received an error message stating: "Failed to load https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterdev&count=10: Response to prefligh ...

Placing miniature vessels within a larger vessel, where two small containers fit on one level of the larger container (refer to images)

I am looking for a way for users to input text in the "your text" container and then click "add". This action should create a new container within the larger red-lined container with the information provided by the user. I know how to do this already, but ...

Tips for eliminating empty trailing values and Carriage Returns from a JavaScript array

I needed a way to eliminate empty elements and Carriage Returns from the end of an array. Here's an example of what my array looks like: Input arr: ['', 'Apple', '', 'Banana', '', 'Guava', & ...