0

I have a JS click function and want to send some data to a python file to process.

In the JS File:

$(#button).click(function(){
  // did some data collection
  $.ajax{
    type: "POST",
    url: "/dummy",
    data: {num: 123},
    success: function(result){
      alert(result);
    }
    error: function(xhr, status, error){
      alert(xhr.status)
    }
  }
})

And in the python file after importing:

app = Flask(__name__)
@app.route('/dummy', methods=['GET', 'POST'])
def dummy(){
  return 1
}
if __name__ == '__main__':
    app.run(debug=True)

I keep getting the alert 0 when clicking the button.

Why the ajax request does not pass through and has a 0 status?

3 Answers3

0

You have to use the route you have mentioned in python file for a specific function to which you want to send data not the file name.

In your case it should be :

url: "/dummy",

It should be methods in route not method

app.route("/dummy",methods=["GET","POST"])

Edit : return a string rather an integer as returning integer is not supported in flask.

def dummy(){
  return "1"
}
charchit
  • 1,492
  • 2
  • 6
  • 17
  • Thank you, I edited it but the status is still 0 and the ajax still has error – Tsang Tsz Hin Jul 22 '21 at 18:44
  • I think the error is that you are returning integer which is not allowed in flask rather return a string `"1"` – charchit Jul 22 '21 at 18:50
  • I changed it to a string but the alert(xhr.status) still pop the message 0 upon clicking the button – Tsang Tsz Hin Jul 22 '21 at 18:58
  • Is there any error in python terninal and you can try logging the error in javascript to see what is the error. – charchit Jul 22 '21 at 19:01
  • I got: Access to XMLHttpRequest at 'file:///C:/dummy' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted. – Tsang Tsz Hin Jul 22 '21 at 19:09
  • How are you running your app. You have to run the python file (python dummy.py), then visit 127.0.0.1:5000 and then you need to make request. And make sure your url should be "/dummy". – charchit Jul 22 '21 at 19:13
  • If you are using external js file then sometimes chrome save cache and flask don't pick up changed file, so do a [hard reload](https://www.documate.org/automation/what-is-a-hard-refresh-how-to-do-a-hard-refresh-in-any-browser/) – charchit Jul 22 '21 at 19:41
  • When I go to the 127 site, the No Found message appears with the requested URL was not on the server. Is there a way to fix it? – Tsang Tsz Hin Jul 22 '21 at 21:27
  • You should visit one this url `127.0.0.1:5000/dummy` as this is the only route in your file. – charchit Jul 23 '21 at 02:30
0

Try turning the 0 in the Python file into a string. Flask usually doesn't allow you to return integers.

app = Flask(__name__)
@app.route('/dummy', methods=['GET', 'POST'])
def dummy(){
  return "1"
}
if __name__ == '__main__':
    app.run(debug=True)

You can turn the string into an integer in JavaScript with the parseInt() function if you need to.

$(#button).click(function(){
  // did some data collection
  $.ajax{
    type: "POST",
    url: "/dummy",
    data: {num: 123},
    success: function(result){
      result = parseInt(result);
      alert(result);
    }
    error: function(xhr, status, error){
      alert(xhr.status)
    }
  }
})
Brendan R.
  • 113
  • 1
  • 6
  • Thank you for responing. However, the python should not return "0". The 0 is by the error of the ajax call – Tsang Tsz Hin Jul 22 '21 at 19:02
  • I think that there is an error in the ajax call because the flask server is returning an integer, which is not allowed by flask. This causes the server to send back an HTTP error 500, which the ajax interprets as an error. – Brendan R. Jul 22 '21 at 19:04
  • I check the error and I got: Access to XMLHttpRequest at 'file:///C:/dummy' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted – Tsang Tsz Hin Jul 22 '21 at 19:11
  • @TsangTszHin Oh! That is because you need to allow the origin with CORS. CORS is used to prevent people from stealing content from other sites. You can do this with flask-cors. This post shows how to do that: https://stackoverflow.com/a/26395623/16450641 – Brendan R. Jul 22 '21 at 21:57
  • @BrendanR. That's not a problem here, he is not running the server or maybe he request to ./dummy.py still. There is no need of flask-cors – charchit Jul 23 '21 at 02:28
  • @charchit if there was no need for flask-cors, why would he be getting a 'blocked by CORS policy' error? In his previous comment, he said "I check the error and I got: Access to XMLHttpRequest at 'file:///C:/dummy' from origin 'null' has been blocked by CORS policy". The problem is most likely he is loading a local html file with the `file://` URL, so the origin is null. – Brendan R. Jul 23 '21 at 13:51
  • So that's the reason why he is getting error , using `file://` , but error says that only these protocols so how would flask-cors solve the error when the protocol isn't supported , he has to run server to make request.`http, data, chrome-extension, edge, https, chrome-untrusted` – charchit Jul 23 '21 at 15:08
0

It seems the issue is actually with CORS. CORS blocks websites from stealing content from other sites by blocking requests with different origins. Because your HTML file is being loaded into the web browser with a file:// URL, CORS is blocking the request there is two ways to solve this.

Option 1: With Flask Cors
Update the python code to allow cross origin requests.

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
corsApp = CORS(app, send_wildcard=True)

@app.route('/dummy', methods=['GET', 'POST'])
@cross_origin()
def dummy():
  return "1"

if __name__ == '__main__':
    app.run(debug=True)

Option 2: Host the HTML file on the local web server

You can also host the HTML file on the local web server, then use that URL to access it.

from flask import Flask, render_template

app = Flask(__name__, template_folder="PATH_TO_HTML_FILE")

@app.route("/")
def home():
    return render_template("NAME_OF_HTML_FILE.html")

@app.route('/dummy', methods=['GET', 'POST'])
def dummy():
  return "1"

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

Then you would access it with 0.0.0.0:5000/ (May change depending on what host/port flask is running on)

Also, Flask can't return integers, only strings.

Brendan R.
  • 113
  • 1
  • 6