0

I have a long polling operation that posts new objects as a JSON just fine, but while getting the updates returning an object, it seems like there is a not-valid JavaScript object I can't parse with jQuery and since it's not valid JavaScript object I can't reach in. Here is console.log I got with the update:

{'body': 'hello world', 'html': '\n<div class="message" id="md1f1cdab-3c3a-4dfe-b268-834aa9981dec"><b>burakdede: </b>hello world</div>\n', 'from': 'burakdede', 'id': 'd1f1cdab-3c3a-4dfe-b268-834aa9981dec'}

Before the response comes out, I am using eval("(" + response + ")") to turn it into a JavaScript object. A show message is used for both posting a new message and getting updates. It works fine with the new posting, but it gives an error when the response comes out.

var updater = {
    errorSleepTime: 500,

    poll: function() {
        var args = {"_xsrf": getCookie("_xsrf")};
        args.listing_id = $(".action").attr("id");

        $.ajax({url: "/a/message/updates", type: "POST", dataType: "text",
                data: $.param(args), success: updater.onSuccess,
                error: updater.onError});
    },

    onSuccess: function(response) {
        try {
            updater.newMessages(eval("(" + response + ")"));
        } catch (e) {
            updater.onError();
            return;
        }
        updater.errorSleepTime = 500;
        window.setTimeout(updater.poll, 0);
    },

    onError: function(response) {
        updater.errorSleepTime *= 2;
        console.log("Poll error; sleeping for", updater.errorSleepTime, "ms");
        window.setTimeout(updater.poll, updater.errorSleepTime);
    },

    newMessages: function(response) {
        if (!response.messages) return;
        var messages = response.messages;
        //console.log(messages.length, "new messages, message is :", messages);
        updater.showMessage(messages);
    },

    showMessage: function(message) {
        var existing = $("#m" + message.id);
        if (existing.length > 0)return;
        var node = $(message.html);
        node.hide();
        $("#inbox").append(node);
        node.slideDown();
    },
};

function newMessage(form) {
    var message = form.formToDict();
    var disabled = form.find("input[type=submit]");
    disabled.disable();

    $.postJSON("/a/message/new", message, function(response) {
        updater.showMessage(response);
        if (message.id) {
            form.parent().remove();
        } else {
            form.find("input[type=text]").val("").select();
            disabled.enable();
        }
    });
}

Rather than fixing on the client side, I fixed the server side code and it is now working. The problem was that it could not produce proper JSON.

1
  • What kind of error do you get and where? Commented Dec 11, 2011 at 12:55

2 Answers 2

1

Specify dataType = 'json' instead of 'text'. jQuery will handle an invalid response for you.

Sign up to request clarification or add additional context in comments.

2 Comments

you mean poll function cause both of ajax queries have dataType=text ?
I mean that why don't use dataType: "json", then the response is an object so that you can use directly response.body, response.html,... And (I think) there is a chance that jQuery handles invalid reponses for you.
0

JSON object properties need to be wrapped inside double-quotes to be valid. Look at the definition of the value in http://json.org.

3 Comments

Are you generating the JSON? Then simply instead of creating something like {name: 'saeed'} or {age: 23}, etc., create something like {"name": "saeed", "age": "23"}. In other words, wrap all property names and all values with double-quotes. This is the safest way.
here is python side code for update it just return dictionary object which should be fine <code>self.finish(dict(messages=str(messages.body)))</code>
Actually the eval Function should handle that Object literal without a problem. JSON specifies double quotes for keys but this is not required in JavaScript per se.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.