0

I'm using an AJAX post like this:

$.ajax({
        type: "POST",
        url: "/AJAXServices.aspx/" + method,
        data: params,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            successfunc();
        },
        error: function(data) {
            errorfunc();
        }
    });

When I use the variable "params" like this:

var params = '{"QuestionID":"' + UpdateQuestion_ID + '", "NewText":"' + newText + '"}';

It works.

But when I change it to this:

var params = { QuestionID: UpdateQuestion_ID, NewText: newText };

This throws an internal server error on the server side:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Server side method:

    [WebMethod]
    public static void UpdateQuestion(string QuestionID, string NewText)
    {
        ....
     }

Any ideas?

2 Answers 2

1

I the first case params is a string and in the second case params is an object.

I guess the server expects a valid json string. Make sure params is an object and use JSON.stringify() to convert it to a valid JSON string before sending it.

$.ajax({
    ...
    data: JSON.stringify(params),
    ...
});
Sign up to request clarification or add additional context in comments.

1 Comment

Works. Thanks @rckrd
1

A JavaScript Object and a JSON looks very similar but have minor difference.

A valid JSON must have key wrapped inside "" but a JS Object Key can be written without "".

Below example is a Valid JS Object but Invalid JSON :

{ name: "Ravi", country: "India" }

So, below is a Valid JSON for same :

{ "name": "Ravi", "country": "India" }

Further, Server Side , it would break as it is a InValid JSON.

You can validate your JSON at http://www.jsoneditoronline.org/

Note : You can convert any JS Object to Valid JSON using

JSON.stringify(JavaScript_Object);

Example :

var a = { name: "Ravi", country: "India" }

Convert from JS-Obj to JSON

var b = JSON.stringify(a);

Now, var b is a valid JSON.

Output : "{"name":"Ravi","country":"India"}"

Comments

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.