Sending JavaScript object as a string to - javascript

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.

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 render template sent as response from Flask app in ajax?

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"

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

Updating info on html page using Ajax in Django

I have a problem with Ajax and how can I update info on my HTML page without reloading it.
So, I have a function in my views.py file:
def index(request):
some stuff
context = {
some stuff
}
return render(request, "header.html", context)
And I just use variables from {context} in my header.html file. And the question is - how can I perform index function and send new variables to my header.html file without reloading it?
First, create a new endpoint to get the desired data in whichever format. I prefer JSON.
New endpoint:
# views.py
from django.http import JsonResponse
def new_endpoint(request):
"""Returns `JsonResponse` object"""
# you can change the request method in the following condition.
# I dont know what you're dealing with.
if request.is_ajax() and request.method == 'GET':
# main logic here setting the value of resp_data
resp_data = {
'html': 'stuff',
# more data
}
return JsonResponse(resp_data, status=200)
Then, you need to code the AJAX part calling this endpoint with the method, data, headers, etc. and finally, define the success callback method to get the desired data.
AJAX:
var data = {};
$.ajax({
url: '/your-new-endpoint-url',
type: 'GET',
data: data,
dataType: 'json',
success: function(resp) {
$('#changingElement').html(resp.html);
}
});
You can send any type of data from this new endpoint to change whatever element's html text or class name or styles, etc.

reload page after processing javascript output in flask

I have a javascript snipped which uses ajax to send an email address to my flask views.py script. I want to send a message to that address if the email is not in my database or otherwise reload the website and show the user information for that email address. Here is my javascript code which sends the data to my views.py
<script type='text/javascript'>
$(".send_invite_message").click(function(evt) {
var Toemail = document.getElementById('To').value
$.ajax({
url: "/send_invitation_member",
type: "GET",
async: true,
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: { email: Toemail},
success: function(data) {
///do something
},
});
});
</script>
and in flask I would like to now have the option to send an email and if the email already exists in the database to reload the site
#app.route('/send_invitation_member', methods=['GET'])
def send_invitation_member():
if request.method == 'GET':
email = request.args.get('email')
search_result = check database for email entry
if search_result:
return render_template('show_members.html')
else:
send message and return json object
However the ajax script expects a json object back, so I don't know how to reload the site and show the user information. Is there any way to do this directly in flask or do I need to extend my javascript code and load the site from there?
thanks
carl
Since there's no way for an AJAX response to directly affect the page that's calling it, you'll need to extend your javascript a little (but only a bit).
In your success function, let's add the following:
success: function(data) {
if (data['url'] != null) document.location = data['url'];
else console.log('Got a valid JSON response, but no URL!');
}
This code will redirect the page to where the JSON specifies with its 'url' key. Now all that's left is to add it to our Flask code.
#app.route('/show_members')
def show_members():
return render_template('show_members.html')
#app.route('/somewhere_else')
def some_other_route():
return "It all works!"
#app.route('/send_invitation_member', methods=['GET'])
def send_invitation_member():
email = request.args.get('email')
search_result = check database for email entry
if search_result:
destination = url_for('.show_members')
else:
destination = url_for('.some_other_route')
send message and return json object
return Response(response=json.dumps({'url': destination}, mimetype='text/json')
I find when using flask it's better to separate your routes out into different functions depending on the HTTP method. And the url_for method? It's a life saver. You can find its docs here http://flask.pocoo.org/docs/0.10/api/#flask.url_for

Categories

Resources