This question already has answers here:
How to manage a redirect request after a jQuery Ajax call
(34 answers)
Replace HTML page with contents retrieved via AJAX
(7 answers)
Closed 4 years ago.
Let's say I have this setup
Why after clicking "arrToPython" button flask does not redirect me to "query_result.html"? And more importantly, how can I make it to do so?
I tried creating separate route like and using flask's "redirect" method, but it did not work for me either :(
test.py:
from flask import Flask
from flask import request, url_for
from flask import render_template
from flask import redirect, Response
app = Flask(__name__)
#app.route('/', methods=['POST', 'GET'])
def savingImage():
if request.method == 'GET':
return render_template('test.html')
if request.method == 'POST':
return render_template('query_result.html')
if __name__ == '__main__':
app.debug = True
app.run()
Where test.html
<!DOCTYPE html> <html> <head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> </head> <body>
<input id="arrToPython" type=button value="arrToPython" href="result" onclick = "arrToPython()">
<script type="text/javascript">
function arrToPython(){
var arr = ['one', 'two']
$.ajax({
type: 'POST',
url: 'http://localhost:5000/',
data: JSON.stringify(arr),
}).done(function(){
console.log('sent');
})
}
</script> </body> </html>
And query_result.html
<br> Hola amigo!</br>
Related
I'm working with Python Flask application that uses basic html and javascript for the web part.
I'm sending data from UI to the backend using ajax post request.
After processing of data, from the Python flask app I'm returning the response with render_template. But I'm not able to understand how that can be rendered using ajax on the web browser.
The python flask API returns this:
#app.route("/execution_pipeline", methods=['POST', 'GET'])
def execution_pipeline():
try:
if request.method == 'POST':
inputMap = request.get_json()
print(inputMap)
###I have my code here###
return render_template('demo.html', location=minio_results_file_location)
except ReferenceError as e:
return "It is a {} Provide proper referaece of file path"
The "demo.html" is a template in the code directory which i want to load on successful execution
And The ajax function is as follows:
$.ajax({
type: "POST",
url: "execution_pipeline",
data: JSON.stringify(data),
contentType : "application/json",
success: function(response) {
window.location.href = response.redirect;
}
});
But on the web page, where we try to load this Ajax response, i'm getting URL not found.
Is there any solution to this?Or am i doing anything wrong?
Import jsonify and url_for from flask:
from flask import jsonify, url_for
And try returning like this to the ajax call:
#app.route("/execution_pipeline", methods=['POST', 'GET'])
def execution_pipeline():
try:
if request.method == 'POST':
inputMap = request.get_json()
print(inputMap)
###I have my code here###
return jsonify({'redirect': url_for('demo.html', location=minio_results_file_location)})
except ReferenceError as e:
return "It is a {} Provide proper referaece of file path"
I have a html file with a search bar, once a button is clicked JavaScript will get the information from that searchbar and use Flask to post it to a python function where I can then use the query from the user to search for a JSON file that has some generated html in it. After finding the JSON file I would then like to return a render_template function for another page passing that JSON data through as a variable.
My main page simplified looks like this
{% extends 'base_layout.html' %}
{% block content %}
<input id="searchbar" placeholder="Search...">
<button onclick="load_generated_html()"><img src='img_src'></button>
{% endblock %}
Later in a JavaScript file I have
function load_generated_html()
{
// Get the data from the searchbar
var searchbar = document.getElementById('searchbar')
// Create and send a json object
var entry = {
file_name: searchbar.value
}
send_json(entry, 'load_generated_html')
}
function send_json(data, url)
{
fetch('http://127.0.0.1:5000/' + url,
{
method: 'POST',
credentials: 'include',
body: JSON.stringify(data),
cache: 'no-cache',
headers: new Headers({
'content-type': 'application/json'
})
})
}
Then finally in a python file
from flask import Flask, render_template, request, make_response, jsonify
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/load_generated_html', methods=['POST', 'GET'])
def load_generated_html():
file_name = request.get_json()['file_name']
html = find_json(file_name)['html']
return render_template('generated.html', name=file_name, html=html)
I then use {{ html }} in generated.html however even though I return render_template nothing happens. I'm still stuck on index.html. I know that the JSON data is getting passed because after some debugging I was able to find out that bit works. But for some reason Flask is not opening generated.html at all. I had a look around at some similar questions on here but none of then seem to have the answer I'm looking for. Thanks for any help you can give me.
You have over-complicated a simple task. There is no need of JS.
Your HTML file should look like this:
{% extends 'base_layout.html' %}
{% block content %}
<form method="post" action="{{url_for('load_generated_html')}}">
<input name="searchbar" placeholder="Search...">
<button type="submit"><img src='img_src'></button>
</form>
{% endblock %}
Your Python code:
from flask import Flask, render_template, request, make_response, jsonify
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/load_generated_html', methods=['POST', 'GET'])
def load_generated_html():
file_name = request.form.get('searchbar')
html = find_json(file_name)['html'] # Assuming find_json is your internal funtion
return render_template('generated.html', name=file_name, html=html)
Goal:
User inputs a personal token in the frontend which should get passed to a python script in the backend. The python script receives the token, places it correctly in it's code and executes. The scripts output should then be returned to the frontend.
I also want to keep the frontend and backend separated.
I've managed to pass information from the frontend to the backend and then received it back in my Chrome console.
Frontend is running at localhost:5500
Backend is running at localhost:5000
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<p>Insert Token: <input id="token">
<button id="send">Send</button>
<script src="app.js"></script>
</body>
</html>
app.js
$("document").ready(function(){
$("#send").click(function(){
var token = $("#token").val();
$.ajax({
url: "http://localhost:5000/token/",
type: "POST",
contentType: "application/json",
data: JSON.stringify({"token": token})
}).done(function(data) {
console.log(data);
});
});
});
views.py
from flask import Flask, request, jsonify
app = Flask(__name__)
#app.route('/token/', methods=['POST'])
def token_input():
response = request.get_json()
print(response)
return jsonify(response)
#app.after_request
def add_headers(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
return response
if __name__ == "__main__":
app.run(debug=True)
So far, my app gives me:
so_far
My guess is:
I have to make a new python script and wrap my script_that_uses_token.py in a function. Then import that function in views.py and somehow use that in the response..?
So I tried javascript below
$(document).ready(function () {
$("#mtime").bind("click", function (e) {
$.getJSON('/test', function(data){
if(data.result==15){
alert("success!");
}else{
alert("fail....");
}
});
});
});
And made route using flask like this
#app.route('/test',methods=[GET,POST])
def test():
return jsonify(result=15)
But when I clicked the 'mtime' , alert method did not work.
And got this message from cmd window
"GET /test HTTP/1.1" 404 -"
How can i make it work?
As PJ Santoro wrote there are the quotation marks missing around GET and POST. However you don't need to add the methods explicitly as you only make a GET request which is the default.
from flask import Flask, render_template, jsonify
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/test')
def test():
return jsonify(result=15)
if __name__ == '__main__':
app.run(host='localhost', port=5000, debug=True)
Also it's better practice if you use url_for in your HTML file to generate the url for your endpoint. This way you can be sure the url changes when you decide to change your subdomain or use a Blueprint.
$(document).ready(function () {
$("#mtime").bind("click", function (e) {
$.getJSON({{ url_for('test') }}, function(data){
if(data.result==15){
alert("success!");
}else{
alert("fail....");
}
});
});
});
Twisted.Web and AJAX
Similar thread already exits . I even took code from there , yet i have the same problem , the twisted server works like a charm, but can't figure out why i can't fetch it with ajax. In similar thread he says that alert comes out , but without data. For me even alert doesn't pop up , yet another ajax functions works , so in general with ajax is everything ok , but exactly with fetching something goes wrong.
As also said in similar thread i can fetch it with curl - $ curl --url http://localhost:8082/test -v , and it shows hello world , so servers works fine 100 % .
Any ideas ?
<script type="text/javascript">
// Submit button
$(function(){
$.ajax({type: "POST",
$('a').click(function(){
url: "http://localhost:8082/test",
data: {},
success: function(data) {alert("Success:" + data);}
});
});
});
</script>
<html>
[...]
Load Favorites Movies...
[...]
</html>
server.py
from twisted.web import server, resource, http
class RootResource(resource.Resource):
def __init__(self):
resource.Resource.__init__(self)
self.putChild('test', TestHandler())
class TestHandler(resource.Resource):
isLeaf = True
def __init__(self):
resource.Resource.__init__(self)
def render_GET(self, request):
return self.render_POST(request)
def render_POST(self, request):
return "hello world!"
if __name__ == "__main__":
import sys
from twisted.internet import reactor
reactor.listenTCP(8082, server.Site(RootResource()))
reactor.run()
Big thank you to Peter Le Bek and Darkporter.
Peter Le Bek asnwer marked as correct , and Darkporter vote up =) from me .
Answer : Peter's answer works out of the box , just the thing that confused me a little bit was the line , where you had to specify the static folder. It is easy ... just sepcify any folder there , put there index.html and it will a root directory , when you access it on the web.
Your javascript is mangled, try this:
wwwdir/index.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.5.2.min.js"></script>
</head>
<body>
click me
<script type="text/javascript">
$('a').click(function(){
$.ajax({type: "POST",
url: "http://localhost:8082/test",
data: {},
success: function(data) { alert("Success: " + data); }
});
});
</script>
</body>
</html>
You'll probably still meet the cross-domain HTTP request restriction mentioned by darkporter, to solve this serve your webpage using the same Twisted server:
server.py
from twisted.web import server, resource, http, static
class TestHandler(resource.Resource):
isLeaf = True
def __init__(self):
resource.Resource.__init__(self)
def render_GET(self, request):
return self.render_POST(request)
def render_POST(self, request):
return "hello world!"
if __name__ == "__main__":
import sys
from twisted.internet import reactor
root = static.File('/path/to/wwwdir')
testHandler = TestHandler()
root.putChild('test', testHandler)
reactor.listenTCP(8082, server.Site(root))
reactor.run()
Is the page your JavaScript lives on served from the same host and port? If not you'll have a cross domain issue.