Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
96
rated 0 times [  99] [ 3]  / answers: 1 / hits: 30742  / 14 Years ago, fri, march 26, 2010, 12:00:00

I'm trying to understand how to build a JSON object in JavaScript. This JSON object will get passed to a JQuery ajax call. Currently, I'm hard-coding my JSON and making my JQuery call as shown here:



$.ajax({
url: /services/myService.svc/PostComment,
type: POST,
contentType: application/json; charset=utf-8,
data: '{comments:test,priority:1}',
dataType: json,
success: function (res) {
alert(Thank you!);
},
error: function (req, msg, obj) {
alert(There was an error);
}
});


This approach works. But, I need to dynamically build my JSON and pass it onto the JQuery call. However, I cannot figure out how to dynamically build the JSON object. Currently, I'm trying the following without any luck:



var comments = $(#commentText).val();
var priority = $(#priority).val();
var json = { comments:comments,priority:priority };

$.ajax({
url: /services/myService.svc/PostComment,
type: POST,
contentType: application/json; charset=utf-8,
data: json,
dataType: json,
success: function (res) {
alert(Thank you!);
},
error: function (req, msg, obj) {
alert(There was an error);
}
});


Can someone please tell me what I am doing wrong? I noticed that with the second version, my service is not even getting reached.



Thank you


More From » jquery

 Answers
27

You may want to look at the JSON JavaScript library. It has a stringify() function which I think will do exactly what you need.


[#97233] Tuesday, March 23, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominickmackenziet

Total Points: 583
Total Questions: 101
Total Answers: 117

Location: Saint Lucia
Member since Wed, Feb 8, 2023
1 Year ago
dominickmackenziet questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Fri, Feb 12, 21, 00:00, 3 Years ago
;