jquery to convert strings to json to send to my webservice? - asp.net

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 function, 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?

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.

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.

Related

How to get post data as json in asp.net?

I am making an ajax request to my API but my API expects raw json data to parse its own objects in C# how do I get the raw Json data in C#? from the "HttpContext.Current.Request"
Here is my request:
$.ajax({
url: '/REST/GetResponse.cshtml',
type: "POST",
contentType: "Application/JSON",
data: {
code: "login",
data: {
username: $("#login_username").val(),
password: $("#login_password").val(),
rememberMe: $("#rememberMe").val()
}
},
success: function (result) {
},
error: function (result) {
console.log(result);
}
});
You should be able to get body of the request using property 'HttpRequest.InputStream`. The type of the property is a stream, but you can see an example on MSDN on how to convert it to string.
Depending of what is your underlying framework there can be easier ways to get the body. E.g. MVC of Web API use binding to map incoming requests to objects, so it might be an option to consider.

How to get remote JSON to work with Kendo grid in ASP.NET

I can successfully make the AJAX call to my service with the following code:
var serverData = { "ZoneParent": "123" };
var request = $.ajax({
type: "POST",
url: "/./Services/Reports.svc/getZones",
contentType: "application/json",
dataType: "json",
jsonp: null,
jsonpCallback: null,
data: JSON.stringify(serverData)
});
request.done(function (msg) {
alert(JSON.stringify(msg));
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
However, when I try to implement the same call with my Kendo grid I get an error
The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'
for getZones. My service call work fine with DataTables, but I want to switch to Kendo potentially. I have messed with this for days to no avail. The application is not MVC. Here is my Kendo code snippet:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/./Services/Reports.svc/getZones",
dataType: "JSON",
data: { zoneParent: "123" },
type: "POST"
},
parameterMap: function (data, operation) {
return kendo.stringify(data);
}
},
schema: {
data: "d"
}
});
var grid = $("#allGrids").kendoGrid({
dataSource: dataSource,
height: 200
});
As cfeduke made similar suggestion you can try to add contentType to the read object of the transport read config just as you did in the $.ajax call.
e.g.
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/./Services/Reports.svc/getZones",
dataType: "json",
contentType: "application/json",
data: { zoneParent: "123" },
type: "POST"
},
parameterMap: function (data, operation) {
return kendo.stringify(data);
}
},
It sounds like the server's reply "Content-type" header is something other than the expected "application/json".
You can use cURL:
curl -v -H "Content-type:application/json" -H "Accept:application/json" \
http://localhost/Services/Reports.svc/getZones
to invoke the endpoint and check the returned header values (-v is verbose, you won't see the headers without it).
Sometimes just setting an "Accept: application/json" header is enough to reveal the problem - either the server coerces the output into JSON or it throws an error that can be tracked down.
I am investigating if there is a another way around this. But seems like Kendo has many limitations and this is one of them. Datables doesn't need a header, just the JSON format.
This is what you need to add to your controller that is sending the data (in case its ajax call)
header("Content-type: application/json");
I wish it wouldn't be like this but Kendo forces this I believe. I prefer datatables, much more freedom and you can customize more.

webservice not returning values to on jquery ajax request

I would like consume cross-domain web-service from client with jquery.here is my code
function getId() {
var testid = ($('#<%=PreviousTest.ClientID %> OPTION:selected').val());
jQuery.support.cors = true;
jQuery.ajax({
type: "POST",
url: "../FalconWebService.asmx/minlatency",
data: "{'testId':" + testid + "}",
contentType: "application/json; charset=utf-8",
dataType:"json",
success: function (data) {
alert("catch");
var msg = jQuery.parseJSON(data.Table);
return msg;
},
Error: function () {
alert("error");
}
my webservice returns values in this format
{"Table":[{"minlatency":16.0,"Time":"/Date(1328248782660+0530)/"},{"minlatency":7.0,"Time":"/Date(1328248784677+0530)/"},{"minlatency":13.0,"Time":"/Date(1328248786690+0530)/"},{"minlatency":6.0,"Time":"/Date(1328248788690+0530)/"},{"minlatency":20.0,"Time":"/Date(1328248790707+0530)/"},{"minlatency":12.0,"Time":"/Date(1328248792723+0530)/"},{"minlatency":26.0,"Time":"/Date(1328248794723+0530)/"},{"minlatency":18.0,"Time":"/Date(1328248796723+0530)/"}]}
Calls in cross-domain work in a different way. They create dynamic javascripts that are inserted to the page using a callback function. This function is used to handle the response from the service. The Jquery calls add a "?callback=?" to the URL of the service, where "callback" is the name of the function that will be inserted.
To call cross-domain services with JQuery you have to do the following:
jQuery.ajax({
type: "POST",
url: "../FalconWebService.asmx/minlatency",
data: "{'testId':" + testid + "}",
contentType: "application/json; charset=utf-8",
dataType: "jsonp", //The data type that you must use is JSONP. Basically tells JQuery that the request is cross-domain
success: function (data) {
alert("catch");
var msg = jQuery.parseJSON(data.Table);
return msg;
},
Error: function () {
alert("error");
},
jsonpCallback: 'callback' //Dude to the fact that the JS is being generated dynamicaly, this tells JQuery to use the name "callback" for the function that will handle the result, as it adds "?callback=?" to the URL
});
You could also use "jsonp" instead of "jsonpCallback" if you want to "override the callback function name in a jsonp request" (from JQuery).
It worked for me (in WCF REST services which communicate with JSON messages, but it should work the same way in your case). This is all explained in the JQuery Ajax documentation.
Hope this helps.

Novice with jQuery AJAX

I am simply learing Ajax with jQuery and have a simple page method that takes in a parameter and returns a string. For some reason, I am not getting the return string but I am getting to my 'success' message:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "testFormMatt.aspx/sayHello",
contentType: "application/json; charset=utf-8",
data: '{"name": "matt"}',
dataType: "json",
success: function(msg) {
$.jGrowl('The web service has been successfully called');
$('#result').append(msg);
}
});
});
When you call append, you need to specify the property of the JSON object that you want to append.
So if your page is returning:
{ message: "Hello, Matt" }
Then you'd need to call append like this:
$("#result").append(msg.message);
If your page is not returning JSON, then you need to take the dataType: "json" out of the $.ajax call. The dataType parameter is for specifying the expected data type of the response, not the data type of the request.

Whats the best way to send array of objects from javascript to webservice?

I have in my javascript these 2 functions "classes":
// product class
function Product() {
this.id;
this.qty;
this.size;
this.option;
}
// room class
function Room() {
this.id;
this.type;
this.products = [];
}
I have my js logic which fills rooms and their products.
Now i want to send array of rooms to a webservice to do some calculations and get back from it the result.
How to send this array objects to the service and whats the data type which the service will receive to loop through and process?
I tried to write the javascript code like this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "_Services/MyWebService.asmx/CalculatePrices",
data: "{'rooms':'" + roomsObjects + "'}",
dataType: "json",
success: function(result) {
alert(result.d);
}
});
And the webservice like this:
[WebMethod]
public string CalculatePrices(object rooms)
{
return "blabla";
}
but i find that rooms in the wbservice is always = [object Object]
For that case this would work:
//...
data : '{"rooms":[' + roomsObjects.join() + ']}',
//...
The above code will generate a valid JSON string, but I recommend you to get a JSON library and use JSON.stringify function:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "_Services/MyWebService.asmx/CalculatePrices",
data: JSON.stringify({'rooms': roomsObjects}),
dataType: "json",
success: function(result) {
alert(result.d);
}
});
If you don't mind including a tiny JavaScript library, I think using json2.js' JSON.Stringify is the best way to serialize objects for use with ASP.NET AJAX services.
Here's a snippet from that post:
// Initialize the object, before adding data to it.
// { } is declarative shorthand for new Object().
var NewPerson = { };
NewPerson.FirstName = $("#FirstName").val();
NewPerson.LastName = $("#LastName").val();
NewPerson.Address = $("#Address").val();
NewPerson.City = $("#City").val();
NewPerson.State = $("#State").val();
NewPerson.Zip = $("#Zip").val();
// Create a data transfer object (DTO) with the proper structure.
var DTO = { 'NewPerson' : NewPerson };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "PersonService.asmx/AddPerson",
data: JSON.stringify(DTO),
dataType: "json"
});
There's no array in that example, but JSON.Stringify does serialize JavaScript arrays in the correct format to send in to ASP.NET AJAX services for array and List parameters.
A nice thing about using JSON.Stringify is that in browser that support native JSON serializing (FF 3.5, IE 8, nightly builds of Safari and Chrome), it will automatically take advantage of the browser-native routines instead of using JavaScript. So, it gets an automatic speed boost in those browsers.
Change:
data: "{'rooms':'" + roomsObjects + "'}",
to:
data: {'rooms':roomsObjects},

Resources