Skip to content

Instantly share code, notes, and snippets.

@MalphasWats
Created July 2, 2012 08:15
Show Gist options
  • Select an option

  • Save MalphasWats/3031823 to your computer and use it in GitHub Desktop.

Select an option

Save MalphasWats/3031823 to your computer and use it in GitHub Desktop.
Making a basic AJAX request with Flask
# Answer to a question on Flask mailing list
# http://librelist.com/browser//flask/2012/6/30/using-ajax-with-flask/
# NOTE: *REALLY* don't do the thing with putting the HTML in a global
# variable like I have, I just wanted to keep everything in one
# file for the sake of completeness of answer.
# It's generally a very bad way to do things :)
#
from flask import (Flask, request, jsonify)
app = Flask(__name__)
html_page = """<!DOCTYPE HTML>
<html>
<head>
<title>Rough AJAX Test</title>
<script>
function loadXMLDoc()
{
var req = new XMLHttpRequest()
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
if (req.status != 200)
{
//error handling code here
}
else
{
var response = JSON.parse(req.responseText)
document.getElementById('myDiv').innerHTML = response.username
}
}
}
req.open('POST', '/ajax')
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
var un = document.getElementById('scname').value
var sec = document.getElementById('secret').value
var postVars = 'username='+un+'&secret='+sec
req.send(postVars)
return false
}
</script>
</head>
<body>
<h1>Flask AJAX Test</h1>
<form action="" method="POST">
<input type="text" name="scname" id="scname">
<input type="hidden" name="secret" id="secret" value="shhh">
<input type="button" value="Submit" onclick="return loadXMLDoc()">
</form>
<div id="myDiv"></div>
</body>
</html>"""
@app.route('/')
def index():
return html_page
@app.route('/ajax', methods = ['POST'])
def ajax_request():
username = request.form['username']
return jsonify(username=username)
if __name__ == "__main__":
app.run(debug = True)
@maximilian-lindsey

Copy link
Copy Markdown

Thank you so much for this awesome Gist! This helped me to finally understand how to send data to my Flask server!

ghost commented Aug 21, 2014

Copy link
Copy Markdown

I agree, thanks for this very useful Gist.

@smaameri

smaameri commented Oct 5, 2014

Copy link
Copy Markdown

Yeah thanks a bunch. After trying to read the data with request.get[ ] for ages, I finally found the answer was as straight forward as request.form[ ]. Thanks!

@jonalxh

jonalxh commented Oct 17, 2017

Copy link
Copy Markdown

Hi. Greetings from Colombia.
Your code have worked for me.

Many forums say that XMLHttpRequests are depreciated, I wanna know if you know how to update the code to current JQuery (Ajax), I've looked for a lot of time and nothing worked.

Thanks a lot.

@mohaam

mohaam commented Mar 19, 2018

Copy link
Copy Markdown

what if the route take varaibles like int:num how we will write the url in open function ?!

@dashvonriprock

Copy link
Copy Markdown

Thanks for writing this. I am porting a 23 year project from PHP to Python/Flask. It is a real help.

@Skyler-Cornell

Copy link
Copy Markdown

What's the intention behind returning the JSON string in the ajax_request method? return jsonify(username=username) Not sure what this is doing! Thanks, this is a great tut

@MalphasWats

Copy link
Copy Markdown
Author

What's the intention behind returning the JSON string in the ajax_request method? return jsonify(username=username) Not sure what this is doing! Thanks, this is a great tut

It's just there to show how you would return some data from the ajax request. If I remember correctly, it needs to be given a header and stuff as part of the request and the jsonify() method handles all of that and makes it accessible in the javascript response object, rather than as plain text that you then have to parse.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment