5

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 

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Cool! Please mark my answer as accepted, or upvote my answer, as that is the best way to say 'thanks' on SO.
Just curious, anyway to achieve this also by passing data, and not modifying the url directly?
0

Using the guidelines provided by Alex G Rice and the answers here Python Flask how to get parameters from a URL? I found out how to pass the data directly as following:

The Ajax call:

$.ajax({ type:"GET", dataType: "json", data:{'name':'Payam'}, url: "http://mypythonapp-spacepirate.rhcloud.com/hello/", success: function(data){ buf1=data; console.log(data); } }) 

The python file:

@app.route('/hello/', methods=['GET','POST']) def hello_world(name=None): buf1 = request.args.get('name') str = {'key':'Hello World!', 'q':buf1} #out = {'key':str} res = json.dumps(str) return res 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.