I am trying to pass javascript variables to python as a directory using the JQuery.ajax and flask application.
index.html
<body>
<label for="fname">First name:</label> <input type="text" id="fname" name="fname">
<label for="lname">Last name:</label><input type="text" id="lname" name="lname">
<button type="submit" onclick='myfunction();'>Click Here to pass your data</button>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
function myfunction() {
const firstname = document.getElementById("fname").value;
const lastname = document.getElementById("lname").value;
const dict_values = {firstname, lastname}
const s = JSON.stringify(dict_values);
console.log(s);
$.ajax({
url:"/test",
type:"POST",
contentType: "application/json",
data: JSON.stringify(s)});
}
</script>
</body>
app.py
import json
from flask import request
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/test', methods=['POST'])
def test():
output = request.get_json()
print(output)
print(type(output))
result = json.loads(output)
print(result)
print(type(result))
return result
if __name__ == '__main__':
app.run(debug=True, host='localhost', port=81)
In console,JSON string looks like this : {"firstname":"c","lastname":"c"}
But I get this error right after:
POST http://localhost:81/test 404 (Not Found)
I am very new to this, I think there is something wrong with the URL path in ajax.
Files path are as follows:
index.html => localhost/index.html
app.py => localhost/venv/scripts/app.py
How can I solve this issue?
Thank you.
I assume that the form data, despite the transfer via AJAX, is also sent to the server as a GET request.
The following example shows you how to send the data to the server with jQuery.
If the form sends a submit event, the default behavior is suppressed with preventDefault
. This means that the actual form is no longer sent.
Then all data of the form are requested and converted into an object. Before sending the POST request using AJAX, this object is converted into JSON format.
The server receives the data and returns it.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form name="my-form">
<div>
<label for="fname">First name:</label>
<input type="text" id="fname" name="firstname">
</div>
<div>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lastname">
</div>
<button type="submit">Click Here to pass your data</button>
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
(function(uri) {
// Wait for the complete document.
$(document).ready(function() {
// Register a listener for the submit event.
$('form[name="my-form"]').submit(function(evt) {
// Suppress the default behavior of the form.
evt.preventDefault();
// Extract the form data and convert it to an object.
const data = {};
$.each($(this).serializeArray(), function(i, item) {
data[item['name']] = item['value'];
});
// Send the data to the server.
$.ajax({
url: uri,
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(data)
}).done(function(data) {
// Receive the reply.
console.log(data);
})
});
});
})({{ url_for('test') | tojson }});
</script>
</body>
</html>
from flask import (
Flask,
jsonify,
render_template,
request
)
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/test', methods=['POST'])
def test():
data = request.json
print(data)
return jsonify(data)