Search code examples
javascriptjqueryasp.netjsonjavascriptserializer

jQuery JSON Posting: Invalid object passed in, ':' or '}' expected


When I am trying to post JSON to server side function then I am getting this error

Invalid object passed in, ':' or '}' expected

I am working ckeditor and this way I am getting data from ckeditor.

var ckEditorCtrl = GetClientID("CKEditor1").attr("id");
var newcontent = getEditorContents(ckEditorCtrl.toString());

function GetClientID(id, context) {
    var el = $("#" + id, context);
    if (el.length < 1)
        el = $("[id$=_" + id + "]", context);
    return el;
}

function getEditorContents(ename) {
    if (CKEDITOR.instances[ename])
        return CKEDITOR.instances[ename].getData();

    var e = $("textarea[id$='" + ename + "']")[0];
    if (e)
            return e.value;

    return false;
}

The HTML I am trying to post capture from ckeditor as follows

<img alt="" src="https://shop.bba-reman.com/wp-content/uploads/2017/05/Toyota-Auris-gearbox-actuator-1-300x300.jpg" style="width: 300px; height: 300px;" /><br />
<br />
We can <strong>REPAIR </strong>your Toyota Auris gearbox actuator

This way I am posting data. Here is the code

$.ajax({
    type: "POST",
    url: "/abcpage.aspx/contentinsert",
        //data: '{"CID":"' + $("[id$='txtContentID").val() + '","CTitle":"' + $("[id$='txtTitle").val() + '","CDesc":"' + $("[id$='txtDesc").val() + '","CKey":"' + $("[id$='txtKeywords").val() + '","CBody":"' + newcontent + '"}',
        data: '{"CID":"' + $("#txtContentID").val() + '","CTitle":"' + $("#txtTitle").val() + '","CDesc":"' + $("#txtDesc").val() + '","CKey":"' + $("#txtKeywords").val() + '","CBody":"' + newcontent + '","OldBody":"' + oldcontent + '"}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        InsertSuccess(msg);
        ComboLoad();
        HideProgressAnimation();

    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        var jsonError = JSON.parse(XMLHttpRequest.responseText);
        alert(jsonError.Message);
        ComboLoad();
        HideProgressAnimation();
    }
});

Solution

  • I would do this before the Ajax request :

    var data = {};
    
    data.CID = $("#txtContentID").val();
    data.CTitle = $("#txtTitle").val();
    data.CDesc = $("#txtDesc").val();
    data.CKey = $("#txtKeywords").val();
    data.CBody = newcontent;
    data.OldBody = oldcontent;
    

    Then:

    $.ajax({
      data: JSON.stringify(data),
      // ...
    

    This would be easier than messing with all these quotes.