Forums

Ajax doesn't run python script... it prints the script

Hi, I am using flask to build a simple app. I try to take inputs from user then use ajax to trigger python to get inputs and run with an output and display on the app. So far, the app keeps printing my python scripts without executing it. Any idea? Thanks in advance!

Can you give more details in terms of how you are trying to trigger the python script?

Thanks for your reply. Here is part of the js (+ajax) code.

function showHint(str) // str is input from user
{  ....
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText; 
    }
  }
xmlhttp.open("GET","/static/test.py"+"/?name="+str,true); // I plan to use xmlhttp to pass along  input str to test.py. 
xmlhttp.send();

#python file
from flask import request
def parse_request():
    data = request.args.get('name') //since pythonanywhere doesn't support cgi. So I guess it's the right way? 
    return data //print out data (which is str) in a different line.

For now, the return is the python script. And I am not sure where is the proper place to save the test.py file. I put it into static folder for now...

Thanks for your help!

so judging from your parse_request python function, it should print out the value of "data". Is that not what you expect?

The current output is :

 from flask import request
    def parse_request():
    data = request.args.get('name') 
    return data

So basically, it returns all my script back to me... I don't know which part is wrong or why the python script fails to execute.

what do you mean it returns your script? what's the exact response?

This is the response:

from flask import request
    def parse_request():
    data = request.args.get('name') 
    return data

It looks like you've set up a static file mapping to serve your Python code rather than using the WSGI file. In your JS code, the URL you're accessing is "/static/test.py" plus a query string. Because you have specified /static/ on the static files table and made it point to a directory, you've told the system that when it receives a request for /static/test.py, it should return the contents of the file test.py in that directory unchanged.

You should change the URL in your JS code to point to a route that is handled by your Flask app rather than to a static file.

Thanks Giles! It makes sense. To just confirm, it is good to put my JS file into the static folder. And one follow up, how should I set up my python code directory into wsgi file? I tried but I still couldn't figure it out... Many thanks!

If you've configured your website as a Flask app on the "Web" page, and left all of the default settings, then your Flask code should go in the flask_app.py file inside the mysite directory -- you can access that from the "Files" page.