Burak Dede
Burak Dede

Reputation: 3743

Valid JSON or JavaScript object to parse

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.

Upvotes: 0

Views: 450

Answers (2)

jcisio
jcisio

Reputation: 507

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

Upvotes: 1

Saeed Neamati
Saeed Neamati

Reputation: 35822

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

Upvotes: 0

Related Questions