user2550979
user2550979

Reputation: 25

ajax returns empty string instead of json [python cgi]

Basically, I have a cgi script that prints out valid json, I have checked and I have a similar functions that work the same way but this one doesn't some reason and I can't find it.

Javascript:

function updateChat(){ 
$.ajax({
            type: "get",
            url: "cgi-bin/main.py",
            data: {'ajax':'1', 'chat':'1'},
            datatype:"html",
            async: false,
            success: function(response) {
                alert(response); //Returns an empty string
            }, 
            error:function(xhr,err)
            {
                alert("Error connecting to server, please contact system administator.");
            }
        });

Here is the JSON that python prints out:

[
"jon: Hi.",
"bob: Hello."
]

I used json.dumps to create the JSON it worked in previous functions that have pretty much the same JSON layout only different content.

There is a whole bunch more of server code, I tried to copy out the relevant parts. Basically I'm just trying to filter an ugly chat log for learning purposes. I filter it with regex and then create a json out of it.

    #!/usr/bin/env python
    # -*- coding: UTF-8 -*-

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

    import cgi, sys, cgitb, datetime, re, time, random, json

    cgitb.enable()

    formdata = cgi.FieldStorage()


    def tail( f, window=20 ): 
        BUFSIZ = 1024
        f.seek(0, 2)
        bytes = f.tell()
        size = window
        block = -1
        data = []
        while size > 0 and bytes > 0:
            if (bytes - BUFSIZ > 0):
                # Seek back one whole BUFSIZ
                f.seek(block*BUFSIZ, 2)
                # read BUFFER
                data.append(f.read(BUFSIZ))
            else:
                # file too small, start from begining
                f.seek(0,0)
                # only read what was not read
                data.append(f.read(bytes))
            linesFound = data[-1].count('\n')
            size -= linesFound
            bytes -= BUFSIZ
            block -= 1
        return '\n'.join(''.join(data).splitlines()[-window:])


    def updateChatBox():
        try:
            f = open('test.txt', 'r')
            lines = tail(f, window = 20)
            chat_array = lines.split("\n")
            f.close()
        except:
            print "Failed to access data"
            sys.exit(4)

        i = 0
        while i < len(chat_array):
            #remove timer
            time = re.search("(\[).*(\])", chat_array[i])
            result_time = time.group()
            chat_array[i] = chat_array[i].replace(result_time, "")
            #Removes braces around user
            user = re.search("(\\().*?(_)", chat_array[i])
            result_user = user.group()
            chat_array[i] = chat_array[i].replace("(", "")
            chat_array[i] = chat_array[i].replace(")", "")
            #Removes underscore and message end marker
            message = re.search("(_).*?(\|)", chat_array[i])
            result_message = message.group()
            chat_array[i] = chat_array[i].replace("_", ":")
            chat_array[i] = chat_array[i].replace("|", "")
            data += chat_array[i] + "\n"
            i = i + 1
        data_array = data.split("\n")
        json_string = json.dumps(data_array)
        print json_string



    if formdata.has_key("ajax"):
        ajax = formdata["ajax"].value
        if ajax == "1": #ajax happens

            if formdata.has_key("chat"):
                    chat = formdata["chat"].value
                    if chat == 1:
                        updateChatBox()
                else:
                    print "ERROR"
                    elif formdata.has_key("get_all_stats"):
                            get_all_stats = formdata["get_all_stats"].value
                            if get_all_stats == "1":
                                getTopScores()
                    else:
                        print "ERROR"

Here is also a function that works perfectly and is in the same python file

def getTopScores():
    try:
        f = open('test_stats.txt', 'r')
        stats = f.read()
        stats_list = stats.split("\n")
        f.close()
    except:
       print "Failed reading file"
       sys.exit(4)

    json_string = json.dumps(stats_list)
    print json_string

The only difference is using the tail function and regex, the end result JSON actually looks identical.

Upvotes: 1

Views: 1121

Answers (1)

Jud
Jud

Reputation: 1188

Are you certain that updateChatBox is even getting called? Note that you compare ajax to the string "1" but you compare chat to the integer 1. I bet one of those doesn't match (in particular the chat one). If that doesn't match, your script will fall through without ever returning a value.

Also, though it isn't the root cause, you should clean up your content types for correctness. Your Javascript AJAX call is declared as expecting html in response, and your cgi script is also set to return content-type:text/html. These should be changed to json and content-type:application/json, respectively.

Upvotes: 1

Related Questions