views:

2220

answers:

2

Hi there,

Trying to figure out how to convert how to covert 5 variables i have in javascript (strings) to a json for sending along to my ajax function

here is my ajax funtion, sill relatively new to this but i believe this should work .. but i need to convert all my strings to a json - don't i?

I believe there are alternative ways of sending data without json, but this is the recommended way isn't it?

                $.ajax({
                type: "POST",
                url: "MyService.aspx/SendEmail",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    alert(msg.d);
                },
                error: function() {
                    alert('error');
                }

            });

I believe that at the service end i need to extract the json - i am using asp.net

Any ideas?

thanks

+4  A: 

You do not need to convert to json to pass the data. Just specify the data you need to pass:

$.ajax({
       url: "myUrl",
        data: {
            var1: "some data or var",
            dataItem2: false // or a variable
        },

        success: function(msg) {
            alert(msg.d);
        },
        error: function() {
            alert('error');
        }
    });

The data will be available as request parameters, like so (in Asp.Net):

Request.Params["var1"]

Now if you truely need to receive json on the server, thats a different issue. If thats a requirement, I would be interested in understanding whay.

Ryan Cook
Thanks! so i need to remove contentType: "application/json; charset=utf-8",dataType: "json",???? whats the default datatype and contentype if not specified..no exactly, i would to know the difference :-) ... JSON is a javascript object.... So hence i am using asp.net on the server... but what about if i need to register a new user with 15 different parameters... is it good practice to create a method with 15 params?? THis is where my doubts lie..
mark smith
The only downside is jQuery doesn't properly convert Objects into Json hashes.
Chris S
+1  A: 

I suggest you to include in your project JSON2.js, that you can find at this link, and to use the JSON.stringify() function:

...
data: JSON.stringify({ yourVar: "value", var2: "value2" }),
...

if your web service return json data you can parse the result with the library:

success: function(json) { json = JSON.parse(json);
                          var o = json.d;
                          ... 
}

It can assure you that your input data will be sanitized from every illegal character.

tanathos