1
votes

I'm attempting to step foot into the web development world, and I'm having some trouble understanding why my basic hello world script is failing. I have a simple AJAX call to a python cgi script that returns a small bit of HTML, but instead the call fails and I get "Internal Server Error" as the error message. Here's my code:

Python script:

#!/usr/local/bin/python

print "Content-Type: text/html\n"
print """\
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
"""

AJAX Call:

$(function(){
            $('#clickme').click(function(){
                $.ajax({
                    url: "cgi-bin/ajaxpost.cgi",
                    dataType: "html",
                    type: "POST",
                    success: function(response){
                        alert(response);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert(errorThrown);
                    }
                });
            });
        });

And here's what my server error logs says:

CGI ERROR: A system problem prevented your request from being completed., referer: [my test page]
Premature end of script headers: ajaxpost.cgi, referer: [my test page]

I double checked with my server and "#!/usr/local/bin/python" is the correct path to python. Additionally, they say they don't have a designated cgi-bin folder, any cgi can run from any folder as long as it has a .cgi extension. EDIT: Also, I have allowed the .cgi to be executed on the server.

I'll go ahead and admit I'm probably going to need an "explain it like I'm five" answer. Thanks!

3
Please.. don't use CGI. It's horrible. You can do webapps in python much, much nicerThiefMaster
I agree that python CGI is horrible; check whether you have unnecessary newlines or whitespaces in your shbang header. from your code it seems like there is an empty line between the header and the first print - try it again after truncating it.thkang
I've removed the extra line to no avail. Still getting the same error.bluefoot
I think I use the same server as you... thank you for posting your exact error, as it lead me here, and solved my (slightly different) problem.Brian Peterson

3 Answers

1
votes

You have a slash character at the end of the first line. Inside triple quotes, that's a literal slash. Remove it.

1
votes

You need two \n at the end of

print "Content-Type: text/html\n"

instead of just one.

Try: print "Content-Type: text/html\n\n"

see https://httpd.apache.org/docs/2.2/howto/cgi.html#writing

1
votes

I just got it working by deleting my .cgi file on the server in WinSCP and re-uploading it fresh instead of just overwriting it between updates. In addition to this, I ensured that it was uploaded as text instead of binary. I suspect this may have been the issue, as perhaps it was preserving the windows text file format. A rookie mistake, I'm sure. Thanks for the help.