0

what is the use of $.toJSON() function. it seems that it convert the data in json format. here is the code snippet

data: $.toJSON({ name: $("input[type=text]").val() })

without using $.toJSON() function we can supply data manually in josn format like

data: { name: $("input[type=text]").val() }

it will also work i think. please discuss. thanks

1

2 Answers 2

2

First, toJSON is not a native jQuery method.

Assuming it does the same as JSON.stringify, it is not the same as assigning an object to the data option. From the documentation (emphasis mine):

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests.

So if you don't pass a string (i.e. the object), the data is converted to a query string, not JSON.

To be more precise

data: $.toJSON({ name: $("input[type=text]").val() })

would result in this URL (assuming GET (%22 is ")):

http://some_server.com/?{%22name%22:%22somevalue%22}

This would make the value difficult to access I suppose. It makes more sense using this ina POST request.

On the other hand,

data: { name: $("input[type=text]").val() }

results in

http://some_server.com/?name=somevalue

Maybe important to point out is that in your example

{ name: $("input[type=text]").val() }

is not "JSON format". It is a JavaScript object literal. JSON is a data exchange format, and although its syntax is similar to JavaScript's object literals, it is something completely different.

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

Comments

2

JSON-format and JSON-object are two different things!

The toJSON (a plugin method) does the following:

toJSON: Serializes a javascript object, number, string, or array into JSON.


  1. data: $.toJSON({ name: $("input[type=text]").val() }) will give you JSON string

  2. data: { name: $("input[type=text]").val() } will give you javascript object

2 Comments

That is for the $.getJSON function, not the $.toJSON function.
@EvanMulawski. what about now?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.