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>