How to render template sent as response from Flask app in ajax? - javascript

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"

Related

Why my flask app is not redirecting after AJAX request?

I am making a web app to help disabled people to navigate the internet. It is taking voice command through a JavaScript and sending the command to the Python app.py Flask app. However, weirdly enough it is not redirecting in any way and giving me 500 internal server error.
This is the JavaScript function which sends command -
// This function sends command to python
function sendCommand(command){
let userCommand = {
"command": command
}
$.ajax({
type: "POST",
url: "/command",
data: JSON.stringify(userCommand),
contentType: "application/JSON",
dataType: 'json',
success: function(){
window.location.href = "temp.html";
}
})
}
And this is the python flask app -
# Importing required libraries and functions
from flask import Flask, render_template, request, redirect
import speech_recognition as sr
import sys
# Initiating Flask
app = Flask(__name__)
# Command Global variable
COMMAND = ""
# Route to Command (Index) page
#app.route("/", methods=["GET", "POST"])
def index():
return render_template("index.html")
# Processing Command
#app.route('/command', methods=["POST"])
def get_javascript_data():
if request.method == "POST":
JSONdict = request.get_json()
COMMAND = JSONdict["command"]
print(f'{COMMAND}', file=sys.stdout)
if "search" in COMMAND:
print("TODOSearch")
elif ("music" and "play") in COMMAND:
print("TODO")
else:
print("TODO")
return redirect("/redirect")
#app.route("/redirect")
def redirect():
return render_template("redirect.html")
What is my fault over here?
You won't be able to redirect from flask on a POST request. Instead use return 200
Then the success function in your Ajax request should trigger.
If you need more flexibility, you can also return json data to the "success" or "error" function.
return json.dumps({'success' : True}), 200, {'ContentType' : 'application/json'}

How to pass data to python scripts from JavaScript?

Here is the HTML file where in scripts portion I made an ajax request to pass some string to python function.
var status = "hello there!!!"
$.ajax({
url: "../SCRIPTS/cond.py",
type: 'POST',
data: {
'status': status
},
success: function (data) {
location.reload(true)
}
});
Here in url I set the path of python scripts. Python file where I want to fetch the requested data from JS and print it.
def main():
#
if __name__ == "__main__":
main()
def test(request):
print(request)
Note: Here I am not using any framework. Just pure HTML, JS and Python file.
Your backend logic(python script in this case) must be hosted on a http server. An "ajax" request is an http request. You can not POST something to a file on the local file system. Are you running your script on a server? If so, you should be able to access it via a http(s):// type URL.

Sending JavaScript object as a string to

I am using AJAX to POST a JSON string to Python Flask but the string doesn't seem to get passed to the flask app.
scoresaver.addEventListener('click', function(ev){
if (scorestate==1) {
var pdata = {'uname':uname, 'score':score.saved}
$.ajax({
type: 'POST',
url: '/',
data: JSON.stringify(pdata),
})
score.saved=null;
scorestate=0;
}
});
On clicking a button the above code is supposed to "send" the JavaScript obj to Python Flask as a string. I have verified that JSON.stringify (pdata) produces the string I require.
#app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
print(request.get_json())
return render_template("index.html")
else:
return render_template("index.html")
This is my code in my Flask application print (request.get_json() comes out to be None.
Please add this key to your ajax call and try again:
contentType: "application/json",
The request's get_json() populates only if the content-type is set to be JSON.

AJAX not changing/redirecting from login page to dashboard [flask backend]

I am using the post method for the login. My ajax function sends the data successfully to my flask backend server [I know because it returns a response to my ajax]. Supposedly, after receiving the respnse from the backend, my ajax success handler will navigate/redirect to the dashboard page but IT DOES NOT! How do I make it navigate/redirect to another page/url?It returns a 200 status code so I do not know why it does not display the dashboard page.
WHAT I HAVE TRIED:
I have tried using window.location.href, window.location.replace but to no avail, still it does not work. I have also tried changing the method to GET but its still the same. I have also set async to false because ajax would not post if I would not set it to false.
AJAX
$.ajax({
type: "POST",
url: 'http://127.0.0.1:5000/processlogin',
data: JSON.stringify(loginobject),
contentType: "application/json;charset=utf-8",
async: false,
success: function (resp) {
window.location.href = ("http://127.0.0.1:5000/dashboard");
},//success
failure: function (resp) {
alert(resp.message);
}
});
backend flask functions
This functions work 100%. Already tested it with POSTMAN. I have also queried the database using my stored procedure and it does well.
This displays the login form
#app.route('/', methods=['GET','POST'])
def login():
return render_template('login.html')
This processes the ajax's sent data. In short this is the function ajax is communicating with
#app.route('/processlogin', methods=['POST'])
def processlogin():
loginobject = request.get_json(force=True)
username = loginobject['username']
password = loginobject['password']
try:
dbpassword = callstoredproc("getpassword", (username,))[0][0]
if dbpassword == 'null':
return jsonify({'status':'error', 'message':'Username does not exist!'})
elif bcrypt.verify(password, dbpassword) == True:
return jsonify({'status':'ok'})
except Exception as e:
print(e)
And this is what I am trying to display: the dashboard html
#app.route('/dashboard', methods=['GET', 'POST'])
def dashboard():
return render_template('dashboard.html')
Remove the curved brackets and try again:
window.location.href = "http://127.0.0.1:5000/dashboard";
It works also with curved brackets so just be sure that your response arrive correctly to the success callback.
See also best answer on SO.
It should also be error instead of failure as error callback.
error: function (resp) {
alert(resp.message);
}
jsfiddle Example

I wanted to get data from server using flask and jQuery

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....");
}
});
});
});

Categories

Resources