1

i want comunicate the views with backend from ajax, i am trying but not show in console the message of backend "HELLO", what is the problem?

       <script type=text/javascript>
        $(function() {
          $('a#test').bind('click', function() {
            $.getJSON('/background_process_test',
                function(data) {
              //do nothing
            });
            return false;
          });
        });
</script>
//button
<div class='container'>
    <h3>Test</h3>
        <form>
            <a href=# id=test><button class='btn btn-default'>Test</button></a>
        </form>

</div>

My backend is this, i am use framework flask

from flask import Flask, jsonify
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app, support_credentials=True)


@app.route('/background_process_test')
@cross_origin(supports_credentials=True)
def background_process_test():
    print "Hello"
    return "nothing"   



if __name__ == "__main__":
  app.run(host='0.0.0.0', port=8000, debug=True)


@app.route("/login")
@cross_origin(supports_credentials=True)
def login():
  return jsonify({'success': 'ok'})

this error i get:

Access to XMLHttpRequest at 'file:///background_process_test' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
  • put your function before `app.run()` (and before `if __name__ == "__main__":)` – furas Aug 05 '19 at 02:55
  • don't you get any error message when you run flask in console/terminal/cmd.exe ? always put full error message (starting at word "Traceback") in question (not comment) as text (not screenshot). There are other useful information. – furas Aug 05 '19 at 02:57
  • @furas no there is no error, the server just listens, use a WSGI production server instead. * Debug mode: activated * Runs at http://0.0.0.0:8000/ (Press CTRL + C to exit) * Restart with stat * The debugger is active! * Debugger PIN: 277-757-720 –  Aug 05 '19 at 03:04
  • do you get `'GGG'` in browser's console when you click `'a#test'` on page ? If it runs AJAX code and it tries to connect to flask then it should display error because it couldn't find `@app.route('/background_process_test')` – furas Aug 05 '19 at 03:08
  • i am using this code https://stackoverflow.com/questions/42601478/flask-calling-python-function-on-button-onclick-event of @Gihan Gamage but now i get this error Access to XMLHttpRequest at 'file:///background_process_test' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. –  Aug 05 '19 at 03:09
  • do you changed code in question ? why ? did you test new code ? maybe it works correctly. – furas Aug 05 '19 at 03:10
  • @furas I want to know why the code of that answer does not work –  Aug 05 '19 at 03:11
  • and I want know if you tested new code - maybe it works and you only waist time . – furas Aug 05 '19 at 03:12
  • @furas with this new code now i get this error Access to XMLHttpRequest at 'file:///background_process_test' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. –  Aug 05 '19 at 03:13
  • how do you display this html ? I don't see template in your code and there is no full URL in html. maybe AJAX try to connect to different server. – furas Aug 05 '19 at 03:14
  • if you get error then you should always put it in question. It may change everything. Previously it displayed nothing , now it display error whcih may help to find problem. – furas Aug 05 '19 at 03:15
  • error show problem with credentials. did you try without credentials ? – furas Aug 05 '19 at 03:17
  • I see `'file:///background_process_test'` - did you run HTML from local file ? It may not have privilages to access server. Why don't use use flask to serve this file ? – furas Aug 05 '19 at 03:18
  • in error is also information that file has to use scheme `http, data, chrome, chrome-extension, https` and it meas it has to be served from server. – furas Aug 05 '19 at 03:19
  • i know not of credentials, is all that code, or ajax is bad? –  Aug 05 '19 at 03:19
  • bad is that you don't serve HTML from server - and then it blocks access to function in flask. All for security reason. – furas Aug 05 '19 at 03:21
  • mmm i am new in flask, how can i solved this, create your answer please –  Aug 05 '19 at 03:24
  • You have to create function which use `return render_template("your_file.html")`. [flask documentation](https://palletsprojects.com/p/flask/). By the way: you have it in you link with code which you use. https://stackoverflow.com/questions/42601478/flask-calling-python-function-on-button-onclick-event – furas Aug 05 '19 at 03:37

1 Answers1

2

After all there was two problems:

  • HTML wasn't serve from flask/server. And browser could block it for security reason. I put HTML directly in function index() but later you can use render_template("filename.html")

  • you forgot to load javascript jQuery library.

In code from your link both elements exists - so you should have already working code: Flask - Calling python function on button OnClick event

from flask import Flask, jsonify
from flask_cors import CORS, cross_origin


app = Flask(__name__)
CORS(app, support_credentials=True)


@app.route('/')
def index():
    return """
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script type=text/javascript>
   $(function() {
     $('a#sender').bind('click', function() {
       $.getJSON('/background_process_test',
         function(data) {
           console.log(data);
           window.alert(data['success'])  
         });
       return false; // stop <a> to send normal request
     });
   });
</script>

<form>
    <a href=# id="sender"><button>Send AJAX</button></a>
</form>

</div>"""

@app.route('/background_process_test')
@cross_origin(supports_credentials=True)
def background_process_test():
    print("Hello AJAX")
    return jsonify({'success': 'OK'})


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8000)
furas
  • 134,197
  • 12
  • 106
  • 148