Passing Arguments from Javascript to Python Function
Question: I am trying to execute/call a python method(with one parameter) from inside
Ajax Call. But I am having trouble passing the parameter from Ajax Call to
Python Function. I am using Flask to connect the two.

Updated Code: Ajax Call(Javascript):

    
    
    $.ajax({
        type: 'GET',
        url: "http://127.0.0.1:5000/get_result/" + input.value,
        dataType: "text",
        success: function(response) {
            output.value = response;
            alert(response);
        }
    }).done(function(data){
            console.log(data);
    });
    

Python Code:

    
    
    from flask import Flask
    app = Flask(__name__)
    
    @app.route("/get_result/<url>", methods=['GET', 'POST'])
    def get_result(url):
        return "Hello World"
    
    if __name__ == "__main__":
        app.run(debug = True)
    

I have a backend Python Server running locally. But I am getting this as the
error. (Running <http://127.0.0.1:5000/get_result/google.com> directly from
browser shows me correct result, if it helps).

[Expected End Result: alertbox with message "Hello World"]

Error:

    
    
    127.0.0.1 - - [03/Dec/2015 13:38:21] "GET /get_result/google.com HTTP/1.1" 200 -
    Error on request:
    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 194, in run_wsgi
        execute(self.server.app)
      File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 185, in execute
        write(data)
      File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 153, in write
        self.send_header(key, value)
      File "/usr/lib/python2.7/BaseHTTPServer.py", line 401, in send_header
        self.wfile.write("%s: %s\r\n" % (keyword, value))
    IOError: [Errno 32] Broken pipe
    

Can you please suggest a work around for this ?

Thanks,


Answer: According to the flask documentation, functions decorated with `@app.route`
don't take a `url` parameter. That explains the error you're getting.

It looks like you need to also do

    
    
    from flask import request
    

so that you can access the request in your function. See here:
<http://flask.pocoo.org/docs/0.10/quickstart/#the-request-object>

Once you do that you can access the data/query params sent over by the ajax
call according to the docs here
<http://flask.pocoo.org/docs/0.10/api/#incoming-request-data>

