I wanted to get data from server using flask and jQuery - javascript

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

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"

How to communicate between python server and javascript client using AJAX and Flask?

I am following this tutorial to communicate between python and javascript. I am a beginner to this so I dont understand what exactly I am doing wrong.
Following is my code in index.html which sends a POST request to the python server side when the button is clicked:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
// setup some JSON to use
var cars = [
{ "make":"Porsche", "model":"911S" },
{ "make":"Mercedes-Benz", "model":"220SE" },
{ "make":"Jaguar","model": "Mark VII" }
];
window.onload = function() {
// setup the button click
document.getElementById("theButton").onclick = function() {
doWork()
};
}
function doWork() {
console.log("posting data")
// ajax the JSON to the server
$.post("receiver", cars, function(){
});
// stop link reloading the page
event.preventDefault();
}
</script>
This will send data using AJAX to Python:<br /><br />
<button type="button" id="theButton">Click Me!</button>
And this is my code on the python side:
import sys
from flask import Flask, render_template, request, redirect, Response
import random, json
app = Flask(__name__)
#app.route('/')
def output():
# serve index template
return render_template('index.html', name='Joe')
#app.route('/receiver', methods = ['GET', 'POST'])
def worker():
print("got some data")
# read json + reply
data = request.get_json()
result = ''
for item in data:
# loop over every row
result += str(item['make']) + ''
return result
if __name__ == '__main__':
app.run()
So, when I press the button in the index.html file, the tutorial says that I will be able to see a server response in the web browser. But even though my server is running, this is what I see in the network tab of developer tools for index.html in the Firefox web browser:
I don't understand what I am doing wrong and how I am supposed to see the communication between the client and server. Any help would be appreciated
Your request is not sending JSON, you have to stringify the cars object to send it as JSON.
function doWork() {
console.log("posting data")
// ajax the JSON to the server
$.post("receiver", JSON.stringify(cars), function(){
}, 'application/json');
// stop link reloading the page
event.preventDefault();
}
I also set the content type to application/json as this is required by request.get_json().
For your network tab issue, you have JS selected so you would not see ajax requests only javascript files. You have to have XHR selected or All.

Post throwing 500 error

I'm writing a small app. Here is the code snippet.
Javascript:
<script type="text/javascript">
function filldata()
{
var sample = document.getElementById("filter-select").value;
jQuery.support.cors = true;
$.post("/test",{"filter_type":sample},function(data,status)
{
alert(data);
});
}
</script>
Flask Code:
#app.route('/test', methods=['POST'])
def test(str):
return str
It is giving me 500 internal error.
When I run this in debug mode, it is saying:
test() takes exactly one argument(zero given)
Your code:
#app.route('/test',methods=['POST'])
def test(str):
return str
Expect a variable named str in input.
With flask, when defining route the arguments of the function represent the url variables:
# the url have a parameter
#app.route('/user/<id>',methods=['GET'])
def test(id): # we get it here
return user.fromId(id)
To retrieve querystring you can use request.args. And to get body request.data or request.json if you are sending json.
from flask import request
#app.route('/test',methods=['POST'])
def test():
return request.data
You need to parse argument from Flask's request object
from flask import request
#app.route('/test',methods=['POST'])
def test():
return request.form.get('filter_type')
See quickstart for more info
In your Flask code snippet, you have added an argument, but arguments are only sent if you change the URL to /test/<str:str>. Since it is a POST request, you can access the data by using request.json.

Ajax POST doesnt work / Twisted

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.

Categories

Resources