Technical Analysis of Resolving "Invalid JSON primitive" Error in Ajax Processing

Nov 22, 2025 · Programming · 11 views · 7.8

Keywords: Ajax | JSON Serialization | jQuery | ASP.NET | Error Handling

Abstract: This article provides an in-depth analysis of the "Invalid JSON primitive" error in jQuery Ajax calls, explaining the mismatch between client-side serialization and server-side deserialization, and presents the correct solution using JSON.stringify() along with compatibility considerations and best practices.

Problem Background and Error Phenomenon

In web development, the "Invalid JSON primitive" error frequently occurs during jQuery Ajax calls. This error typically arises when the client sends JSON data to the server, but improper serialization causes the server to fail in parsing the data correctly. Specifically, when the client uses Sys.Serialization.JavaScriptSerializer.serialize(obj) to generate a JSON string and sends it via $.ajax, the ASP.NET JavaScriptSerializer.Deserialize method on the server side cannot recognize the data format, throwing an "Invalid JSON primitive" exception.

Root Cause Analysis

The fundamental cause of the error is the mismatch between client-side serialization and server-side deserialization. When Sys.Serialization.JavaScriptSerializer.serialize(obj) generates a JSON object, jQuery, by default, converts the data object into URL-encoded format (e.g., foo=foovalue&bar=barvalue) during the Ajax request, rather than preserving the original JSON string format. This results in the server receiving URL-encoded data instead of the expected JSON string, making correct deserialization impossible.

Solution and Code Implementation

To resolve this issue, it is essential to ensure that the data sent from the client is a standard JSON string, not URL-encoded data transformed by jQuery. It is recommended to use the JSON.stringify() method to serialize the JavaScript object into a JSON string and pass it directly as a string to the data parameter.

Example of the modified jQuery function:

function DeleteItem(RecordId, UId, XmlName, ItemType, UserProfileId) {
    var obj = {
        RecordId: RecordId,
        UserId: UId,
        UserProfileId: UserProfileId,
        ItemType: ItemType,
        FileName: XmlName
    };
    var json = JSON.stringify(obj);

    $.ajax({
        type: "POST",
        url: "EditUserProfile.aspx/DeleteRecord",
        data: json,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        cache: false,
        success: function(msg) {
            if (msg.d != null) {
                RefreshData(ItemType, msg.d);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("error occured during deleting");
        }
    });
}

In this code, JSON.stringify(obj) converts the JavaScript object into a standard JSON string, which jQuery sends as a raw string without additional encoding transformations. The server-side WebMethod remains unchanged, and the ASP.NET framework can correctly parse the JSON string and map it to the method parameters.

Compatibility Considerations and Best Practices

Although modern browsers generally support JSON.stringify(), older browsers (such as IE7 and below) may lack this method. To ensure compatibility, the json2.js library can be introduced, providing standard JSON serialization and deserialization functionalities to compensate for the lack of native browser support.

Furthermore, the conflict between infinite scrolling and RadRating controls mentioned in the reference article highlights the importance of maintaining consistent data formats between client and server in dynamic content loading scenarios. Similarly, in Ajax calls, it is crucial to strictly control the serialization method to avoid parsing errors caused by format mismatches.

Conclusion

The core of the "Invalid JSON primitive" error lies in the format mismatch between client-side serialization and server-side deserialization. By using JSON.stringify() to ensure the transmission of standard JSON strings and incorporating compatibility libraries for older browser support, such errors can be effectively avoided. Developers should always pay attention to data format consistency during Ajax interactions to ensure system stability and compatibility.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.