FrancesKR
FrancesKR

Reputation: 1210

Internal Server Error when retrieving JSON from a python script using JQuery

I'm trying to write a simple web application that uses JQuery to call a python script. The python script returns data in JSON format. Here is the ajax call in my Javascript:

console.log('before');

$.ajax({
    dataType: "json",
    url: "simple.py",
    success: function() { alert("Success"); },
    error: function(request, error) { console.log(request); }
});

console.log('after');

Here is my python script:

#!/usr/bin/env python
import json

l = "hello"
print json.dumps(l)

When I run the Javascript, I get an "Internal Server Error". The same thing happens if I change dataType to "script" in my ajax call, or change print to return.

When I instead use a plain JSON file like this one that I got from some example online:

{
  "one": "Singular sensation",
  "two": "Beady little eyes",
  "three": "Little birds pitch by my doorstep"
}

with dataType: "json" and url: "test.json", it works fine. When I use a python script that prints out a bunch of HTML instead of JSON, that works fine too. When I run simple.py on its own from the command line, it prints out the result the way it should as if nothing's wrong. However, for some reason my JQuery just won't receive JSON data. In the Web Inspector, under "Network", the type of simple.py is listed as text/html, which seems incorrect. I think this should maybe be application/json but I'm not sure how to change it.

I'm using the Apache2 server that comes with Mac OSx, and I've put all my website files under Library/WebServer/Documents. I'm accessing my website through the "localhost" url.

Errors in log:

(8)Exec format error: exec of '/Library/WebServer/Documents/UBCNetworks/simple.py' failed, referer: localhost/UBCNetworks/index.html
 .... Premature end of script headers: simple.py, referer: localhost/UBCNetworks/index.html 

Upvotes: 0

Views: 1759

Answers (1)

FrancesKR
FrancesKR

Reputation: 1210

Solved this! I had to add the following line to my python script:

print "Content-type: application/json\n\n";

This was apparently what the "Premature end of script headers" error meant... this was the script header that was missing. My javascript now prints out "Success!" as well as "hello", the JSON object returned by the python script. In the Web Inspector, the type of simple.py is now application/json instead of text/html.

(Thanks Barmar for the help!)

Upvotes: 2

Related Questions