Search code examples
pythonjqueryajax

What is causing a jQuery Ajax call to a Python script to throw a 500 error?


I have a website that has a jQuery Ajax call to a Python script. When I call it, it returns a 500 error. Note that the Python script itself works when submitted through a cron job; it is only when trying to call it through Ajax does the error appear.

Excerpt of the HTML page that makes the call:

<!DOCTYPE html>
<html>
<head>
<title>Python Test</title>
<script src="jquery-3.3.1.js"></script>
</head>
<body>
<div id="the_output">The text returned from the Python script goes here</div>

<script>

$.ajax({
         url:"cgi-bin/PythonTest.py",
         type:"POST",
         success:function(data) {
             try {
                 document.getElementById("the_output").innerHTML = data;
             }
             catch (e) {
                 document.getElementById("the_output").innerHTML = "<b>Error parsing data:</b><br />" + data;
             }
         },
         error:function(xhr, status, error) {
            let errorMessage = "<b>Query returned a failure:</b><br />"
                             + "Status: " + status + "<br />"
                             + "Error: " + error + "<br />"
                             + "XHR Response Text:<br />{" + xhr.responseText + "}";
            document.getElementById("the_output").innerHTML = errorMessage;
         }
       });
</script>

</body>
</html>

And PythonTest.py:

#!/usr/bin/env python3

print("<br />If you can read this, then It Works<br />")

When I enter the URL of the page in a browser, what comes back is:

Query returned a failure

Status: error

Error: Internal Server Error

and the XHR Response has the HTML of the web host's page for a 500 error.

Should I be adding something to the Ajax call?

EDIT: When I enter the URL directly into a browser, it returns the same 500 error page that the Ajax call returns. It doesn't appear to be browser-specific, as it happens with Edge, Firefox, and Chrome. Also, I did check to make sure the line terminators in the script are Unix-style, not DOS-style, and I don't have any problem running PHP scripts on it - just Python.


Solution

  • I asked the boffins at the web server, and they said that I needed to include:

    print("Content-type: text/html\n")
    

    to the start of my Python script (after the call). I did, and it works.