How to Send JSON Instead of a Query String with $.Ajax

How to send JSON instead of a query string with $.ajax?

You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:

$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});

Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.

Trying to send JSON using $.ajax, sends query string instead

When you pass a manually-serialized JSON string, jquery will automatically URLEncode your data.

I suggest you JSON.stringify it

$.ajax({
contentType: "application/json",
method: "POST",
url: "/test",
dataType: "json",
data: JSON.stringify(dat),
success:function(res){
console.log(res);
}
});

Send JSON using Ajax in Querystring along with regular params

Due to the amount of data you want to pass over (12 params) with potentially a lot of data, you may want to use POST rather than GET.

Examples of AJAX POST

var myObj= { "Name" : "John", "Age" : "22" }; //Array with similar properties to your Model

$.ajax({
url : "/GetData/",
type: "POST",
data : myObj,
success: function(data, textStatus, jqXHR)
{
//data - response from server
},
error: function (jqXHR, textStatus, errorThrown)
{

}
});

and ensure that your Action is accepting the HTTP POST verb.

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult GetData(string id, string a, myObj myObj)
{
}

See this reference for additional info.

jquery $.post second argument. - json or query string?

In general both ways are in practice very close. The function $.post or $.ajax will encode the data posted in the same way. If you want to post JSON data you should additionally encode the data value with some JSON encoder. See How do I build a JSON object to send to an AJAX WebService? as an example ($.post is a short form of $.ajax, so all which described with $.ajax and correct also for $.post)

$.post('somescript.php', { data: JSON.stringify($('#myInputField').val()) }, ...);

In the code above I use JSON.stringify from http://www.json.org/js.html.

UPDATED: After your questions in the comment I hope I understand more which you want to know. So jQuery.post don't makes any JSON encoding of data for you for and input parameters (the second parameter of jQuery.post). So it send the data always exactly in the same way. You can add additional "json" parameter (the last dataType parameter) to the $.post call, but this will not change how the data will be encoded.

The question "should I send JSON data to the server or not?" is independent on $.post and you should answer on the question yourself depend on the requirement existing in your project. Sometime it is the question of the architecture of your solution. Sometime you have to choose one special way.

In case of Microsoft ASMX Web Service for example there exist some important restriction. For example you want to deliver JSON data from the web service to be able to work easy with the data in JavaScript. So you want to have a method on the server side which have some input parameters and returns JSON as output. In case ASMX Web Service you must sent all input parameter to the web service method as JSON encoded data to be able to return JSON data from the web service, but ASMX Web Service decode/encode the data for you and you don't need manually encode/decode JSON on the server side.

Why json data of ajax call ended up as querystring parameter?

Change the type of your request to a post.

  $.ajax({
type: "POST",
url: "StatusService.svc/CheckStatus",
data: JSON.stringify({"companyName":"paymins"}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('ok!');
alter(data.toString());
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ' / ' + errorThrown);
}
});

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.



Related Topics



Leave a reply



Submit