I am trying to reproduce the simply jQuery example from the Flask docs: https://flask.palletsprojects.com/en/1.1.x/patterns/jquery/. It works fine on my local machine, but when I host it on a web server in cgi-bin, getJSON returns false. How can I correct this? Thank you!
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
#app.route('/_add_numbers')
def add_numbers():
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a + b)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run()
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<script type=text/javascript>
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
</script>
<script type=text/javascript>
$(function() {
$('a#calculate').bind('click', function() {
$.getJSON($SCRIPT_ROOT + '/_add_numbers', {
a: $('input[name="a"]').val(),
b: $('input[name="b"]').val()
}, function(data) {
$("#result").text(data.result);
});
return false;
});
});
</script>
<h1>jQuery Example</h1>
<p><input type=text size=5 name=a> +
<input type=text size=5 name=b> =
<span id=result>?</span>
<p><a href=# id=calculate>calculate server side</a>
Related
I have a flask application that I am trying to send some json to the browser and render it. But the line with $.getJSON() is not running. The jist of which is below:
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index_html():
data = {"this":"is", "just":"a test"}
return render_template('index.html', data=data)
if __name__ == '__main__':
app.run(debug=True)
index.html
<html>
<head>
<script src="{{url_for('static', filename='jquery-3.5.1.min.js')}}"></script>
<script src="{{url_for('static', filename='leaflet/leaflet.js')}}"></script>
<link rel="stylesheet" href="{{url_for('static', filename='leaflet/leaflet.css')}}">
<link rel="stylesheet" href="{{url_for('static', filename='app.css')}}">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
<h1>My test that doesn't work</h1>
<div id="llmap"></div>
<script src="{{url_for('static', filename='app.js')}}"></script>
</body>
app.js
console.log("before")
$.getJSON("/", function(data){
console.log("during")
console.log(JSON.stringify(data));
});
console.log('after')
Console OUTPUT
before
after
Even if my data were somehow messed up, i'd expect at least to see
before
during
after
What am I not understanding here, why isn't getJSON() firing?
You are using
return render_template('index.html', data=data)
You need to return ONLY data when you call the .getJSON function. simple
return data
should work. Because getJSON doesn't allow POST request you'll have to add one more route
#app.route('/')
def index_html():
return render_template('index.html')
#app.route("/getjson")
def json():
data = {"this":"is", "just":"a test"}
return data
and change your getJSON request to
$.getJSON("/getjson", function(data){
console.log("during")
console.log(JSON.stringify(data));
});
I'm trying to make a chat application with flask and socketio but I get an Uncaught ReferenceError: io is not defined error in my web browsers inspector. Googling this error didn't give me much.
Here is my python code:
import requests
from flask import Flask, jsonify, render_template, request
from flask_socketio import SocketIO, emit
# Configure Flask-socketio
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
#socketio.on('message')
def handleMessage(message):
print('Message: ' + message)
send(message, broadcast=True;)
if __name__ == '__main__':
socketio.run(app)
And here is my html code:
<html>
<head>
<title>Test flask-socketio</title>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
</head>
<body>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', () => {
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
//When connected, configure submit button to emit message event
socket.on('connect', () => {
socket.send('User has connected!');
});
});
</script>
<ul id="messages"></ul>
<input type="test" id="myMessage">
<button id="sendbutton">Send</button>
</body>
</html>
Does anybody know why I get this error?
Problem is that you are not getting the socket.io here. Below is correct HTML File code for you
<html>
<head>
<title>Test flask-socketio</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', () => {
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
//When connected, configure submit button to emit message event
socket.on('connect', () => {
socket.send('User has connected!');
});
});
</script>
<ul id="messages"></ul>
<input type="test" id="myMessage">
<button id="sendbutton">Send</button>
</body>
</html>
I have updated the Address of Scripts here.
You will be getting cors error next, Goodluck.
I have a python script and apache web server running in a raspberry pi. I want to change the value of a variable in my python script from a web page using javascript. It is possible?
We can use socket. for easily using socket, we can use socket.io
Start.html
<!doctype html>
<html>
<head>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
</head>
<body>
<h1>Socket.IO GPIO control</h1>
<button id="btnGpio">Change GPIO</button>
<script>
var socket = io.connect('http://localhost:5000');
var index = 0;
socket.on('connect', function () {
console.log('connected')
document.getElementById('btnGpio').addEventListener('click', () => {
index = index + 1;
console.log('index', index)
socket.emit('change_gpio', { status: (index % 2 == 0) })
})
});
</script>
</body>
</html>
socket_server.py
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
#app.route("/")
def home():
return render_template("Start.html")
socketio = SocketIO(app)
pin = True
#socketio.on('change_gpio')
def handle_my_custom_event(json):
pin = json['status']
print('pin = ' , pin)
#socketio.on('connect', namespace='/')
def test_connect():
print('Connected')
if __name__ == '__main__':
socketio.run(app)
Install library with pip
pip install flask
pip install flask-socketio
Document:
https://flask-socketio.readthedocs.io/en/latest/
Basically I want the code below to put the "search" from the backend to the frontend.
I am having trouble getting my flask app to pass data from the back end to the front end using templates and a simple flask structure.
I am open to suggestions for better ways. Also # Daniel Mesejo has been a great help so far in my learning about Flask and ajax/jquery.
here is my app.py
from scraper import scrape
from flask import Flask, render_template, jsonify, make_response, request
import json
app = Flask(__name__)
#app.route("/", methods=['GET', 'POST'])
def index():
entries = json.dumps(scrape("video games"))
return render_template('index.html', entries= entries)
#app.route('/parse_data', methods=['GET', 'POST'])
def parse_data():
if request.method == "POST":
#data = request.form("blah")
#print("blah")
search = request.get_json()
#new_search = json.dumps(scrape(data))
return jsonify(search)
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=5000)
here is my index.html
<!DOCTYPE html>
<html>
<head>
<title>Flask app</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="topnav">
<a class="active" href="#home">Home</a>
About
Contact
<form class = "form" action="" method="POST">
<input id ="textbox" name="textbox" type="text" placeholder="Search..">
<button type="submit">submit</button>
</form>
</div>
<p>you searched: {{search}} </p>
<div id="div1">
<p id="p1"></p>
<p id="p2"></p>
</div>
<script>
var value = $('.textbox').val();
//alert(value);
$("button").click(function (e) {
e.preventDefault();
var value = $("#textbox").val();
alert(value);
$.ajax({
type: 'POST',
url: "parse_data",
data: JSON.stringify({"text" : value}),
contentType: 'application/json; charset=utf-8',
success: function(data){
alert(JSON.stringify(data));
}
});
});
var jsonz = {{ entries|tojson }};
var s = JSON.parse(jsonz);
var i;
for (i = 0; i < s.length; i++) {
var para = document.createElement("p");
var node = document.createTextNode(s[i].product_name + "\n" + s[i].product_link);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
}
//document.getElementById("user").innerHTML =
//obj;
//"Name: " + obj.product_name + "<br>" +
//"Location: " + obj.product_link;
</script>
</body>
</html>
To achieve want that simply change the function you pass to success like this:
success: function (data) {
$("#search-query").text("you search: " + data["text"]);
}
and change the <p> element to <p id="search-query"> you searched: </p>.
To learn more about Flask and web development in general I suggest the Flask Mega Tutorial, in here.
I'm developing a web application that takes a grayscale input and return a colorized version of that image using machine learning. For that, the web app is with a python backend linking the front end html pages using the Flask microframework.
I'm sending the image I choose to process in python and then return the image name to display it from its directory. My question is how can I make the previous operations happen without reloading the html page?
I made a minimal working example, which does the exact thing you're asking:
from flask import Flask, render_template_string, request, jsonify, url_for
import os
from werkzeug.utils import secure_filename
if not os.path.isdir("/static"): # just for this example
os.makedirs("/static")
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
file = request.files['file']
fname = secure_filename(file.filename)
file.save('static/' + fname)
# do the processing here and save the new file in static/
fname_after_processing = fname
return jsonify({'result_image_location': url_for('static', filename=fname_after_processing)})
return render_template_string('''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" name="fileinfo">
<label>Some user provided information</label>
<input type="text" name="some_info" size="12" maxlength="32" /><br />
<label>File to upload:</label>
<input type="file" name="file" required />
<input type="submit" value="Upload the file!" />
</form>
<img id="resultimg" scr="">
<div></div>
<script>
var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function(ev) {
var oData = new FormData(form);
var oReq = new XMLHttpRequest();
oReq.open("POST", "{{url_for('index')}}", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
document.getElementById('resultimg').setAttribute('src', JSON.parse(oReq.responseText).result_image_location);
} else {
alert("Error " + oReq.status + " occurred when trying to upload your file")
}
};
oReq.send(oData);
ev.preventDefault();
}, false);
</script>
</body>
</html>
''')
app.run()
I'm not checking for file extensions or overwriting files, so you should secure this feature quite a bit more. But the basic infrastructure is there.