I am experimenting with Flask and AJAX, I have a simple API route here , hosted at OpenShift. I want to call the API in a Javascript file with Ajax. The OpenShift Python file is simple:
from flask import Flask
app = Flask(__name__)
import json
@app.route('/hello/<name>')
def hello_world(name=None):
str = {'key':'Hello World!', 'q':name}
#out = {'key':str}
res = json.dumps(str)
return res
if __name__ == '__main__':
app.run()
And here is the Ajax call:
$.ajax({
type:"GET",
dataType: "json",
data:'Payam',
url: "http://mypythonapp-spacepirate.rhcloud.com/hello/",
success: function(data){
buf1=data;
console.log(data);
}
})
But this makes a call to this url which results in 404. How can I solve this? Just to mention CORS is not an issue.
http://mypythonapp-spacepirate.rhcloud.com/hello/?Payam
We can also use Ajax to handle the user input rather than rendering a template. After carrying out the calculation client-side we will then pass the user input and results to the server to store in a database.
Flask is a popular micro framework for building web applications. Since it is a micro-framework, it is very easy to use and lacks most of the advanced functionality which is found in a full-fledged framework. Therefore, building a REST API in Flask is very simple.
From IDEA to Product Using Python / Django Ajax essentially is a combination of technologies that are integrated together to reduce the number of page loads. We generally use Ajax to ease end-user experience. Using Ajax in Django can be done by directly using an Ajax library like JQuery or others.
This template will load jQuery as above and have a little form where we can add two numbers and a link to trigger the function on the server side. Note that we are using the get() method here which will never fail. If the key is missing a default value (here 0 ) is returned.
Try changing your url property to
url: "http://mypythonapp-spacepirate.rhcloud.com/hello/world",
Then you will get a 200 response status, instead of the 404. The reason is the flask route you created has a required parameter after the hello/.
edit: followup to question about using variable for the data
method1: just add encode the parameter to the url
url: "http://mypythonapp-spacepirate.rhcloud.com/hello/" + encodeURIComponent(xyz)
method2: use the data
parameter to the ajax call as you have started to do. I think that jquery will translate that into the URL query string for a get
, like this. Notice the ?
delimiting the start of query string:
http://mypythonapp-spacepirate.rhcloud.com/hello/?xyz
You can verify that by checking in your browser dev tools and seeing what URL the ajax call is actually requesting. Also note that in the flask handler you would then need to check for request.query_string to get the data, because <name>
parameter would be empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With