How to Build a JSON Object to Send to an Ajax Webservice

How do I build a JSON object to send to an AJAX WebService?

The answer is very easy and based on my previous posts Can I return JSON from an .asmx Web Service if the ContentType is not JSON? and JQuery ajax call to httpget webmethod (c#) not working.

The data should be JSON-encoded. You should separate encode every input parameter. Because you have only one parameter you should do like following:

first construct you data as native JavaScript data like:

var myData = {Address: {Address1:"address data 1",
Address2:"address data 2",
City: "Bonn",
State: "NRW",
Zip: "53353",
{Code: 123,
Description: "bla bla"}}};

then give as a parameter of ajax request {request:$.toJSON(myData)}

$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://bmccorm-xp/HBUpsAddressValidation/AddressValidation.asmx/ValidateAddress",
data: {request:$.toJSON(myData)},
dataType: "json",
success: function(response){
alert(response);
}
})

instead of $.toJSON which come from the JSON plugin you can use another version (JSON.stringify) from http://www.json.org/

If your WebMethod had parameters like

public Response ValidateAddress(Request request1, Request myRequest2)

the value of data parameter of the ajax call should be like

data: {request1:$.toJSON(myData1), myRequest2:$.toJSON(myData2)}

or

data: {request1:JSON.stringify(myData1), myRequest2:JSON.stringify(myData2)}

if you prefer another version of JSON encoder.

Jquery Ajax Posting JSON to webservice

You mentioned using json2.js to stringify your data, but the POSTed data appears to be URLEncoded JSON You may have already seen it, but this post about the invalid JSON primitive covers why the JSON is being URLEncoded.

I'd advise against passing a raw, manually-serialized JSON string into your method. ASP.NET is going to automatically JSON deserialize the request's POST data, so if you're manually serializing and sending a JSON string to ASP.NET, you'll actually end up having to JSON serialize your JSON serialized string.

I'd suggest something more along these lines:

var markers = [{ "position": "128.3657142857143", "markerPosition": "7" },
{ "position": "235.1944023323615", "markerPosition": "19" },
{ "position": "42.5978231292517", "markerPosition": "-3" }];

$.ajax({
type: "POST",
url: "/webservices/PodcastService.asmx/CreateMarkers",
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify({ Markers: markers }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert(data);},
error: function(errMsg) {
alert(errMsg);
}
});

The key to avoiding the invalid JSON primitive issue is to pass jQuery a JSON string for the data parameter, not a JavaScript object, so that jQuery doesn't attempt to URLEncode your data.

On the server-side, match your method's input parameters to the shape of the data you're passing in:

public class Marker
{
public decimal position { get; set; }
public int markerPosition { get; set; }
}

[WebMethod]
public string CreateMarkers(List<Marker> Markers)
{
return "Received " + Markers.Count + " markers.";
}

You can also accept an array, like Marker[] Markers, if you prefer. The deserializer that ASMX ScriptServices uses (JavaScriptSerializer) is pretty flexible, and will do what it can to convert your input data into the server-side type you specify.

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

Create a model

public class Person
{
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}

Controllers Like Below

    public ActionResult PersonTest()
{
return View();
}

[HttpPost]
public ActionResult PersonSubmit(Vh.Web.Models.Person person)
{
System.Threading.Thread.Sleep(2000); /*simulating slow connection*/

/*Do something with object person*/

return Json(new {msg="Successfully added "+person.Name });
}

Javascript

<script type="text/javascript">
function send() {
var person = {
name: $("#id-name").val(),
address:$("#id-address").val(),
phone:$("#id-phone").val()
}

$('#target').html('sending..');

$.ajax({
url: '/test/PersonSubmit',
type: 'post',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$('#target').html(data.msg);
},
data: JSON.stringify(person)
});
}
</script>

how to pass JSON data to restful web services through ajax and also how to get JSON data?

var JSONObject= {"uname":uname, "password":password };
var jsonData = JSON.parse( JSONObject );

var request = $.ajax({
url: "rest/orders",
type: "POST",
data: jsonData,
dataType: "json"
});

Sending a JSON object to an ASP.NET web service using JQUERY ajax function

Step 1, client side:
You have to serialize your client objects into JSON, I personally use stringify() method of the JSON2 library: http://www.json.org/js.html

data: JSON.stringify(myObj)

Step2, Server-side: You have to translate the serialized object into something "eatable" by your c# code. Here you can use deserialize() method of Microsoft's JavaScriptSerializer class (but it might have some issues in .net 3.5 if you don't have SP installed), or otherwise JSON.net library http://james.newtonking.com/pages/json-net.aspx

server-side method signature should be:

fSaveToDB(Object myObj)

where "myObj" is the name of your client-side object container:

{myObj: your object...}


Related Topics



Leave a reply



Submit