How to pass a JSON array in javascript to my codebehind file - c#

I am getting a JSON object in my javascript function in aspx page. I need to fetch this data from my code behind file. How can I do it?
My javascript function is :
function codeAddress()
{
var address = document.getElementById("address").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location });
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
var requestParameter = '{' +
'output:"' + results + '"}';
$.ajax({
type: "POST",
url: "Default.aspx/GetData",
data: requestParameter,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
},
error: function() { alert("error"); }
});
});
}
Default.aspx.cs
[WebMethod]
public static string GetData( Object output)
{
return output.ToString();
}
I am getting the output as an array of objects instead of the actual result - [object Object],[object Object],[object Object] .Please provide me a solution to get the actual result. The JSON I am working on is given below
http://maps.googleapis.com/maps/api/geocode/json?address=M%20G%20Road&sensor=false

Create a WebMethod on your aspx Page that get the array on the page as:
[WebMethod]
public static GetData( type[] arr) // type could be "string myarr" or int type arrary - check this
{}
and make json request.
$.ajax({
type: 'POST',
url: 'Default.aspx/GetData',
data: "{'backerEntries':" + backerEntries.toString() + "}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(response) {}
});
or you can use .post().
Check the url: in ajax request GetData WebMethod must be declared on the Default.aspx on that page where you are making ajax request.
Check this question to know that how to format array for sending to the web method.
Why doesn't jquery turn my array into a json string before sending to asp.net web method?
Check these links for reference:
Handling JSON Arrays returned from ASP.NET Web Services with jQuery - It is Best to take idea
How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

Related

How to get data from POST url ajax

Using ajax POST a url http://test/jy/post.php will get some value below
People,1220,temperature,26C,CO2 concentration,30ppm,3.jpg
Want to put each of them separately into my input text.
Trying to alert data, but it show [object],don't know how to do.
Here is my js:
window.onload = load();
function load() {
$.ajax({
url: 'http://test/jy/post.php',
type: 'POST',
success: function (data) {
},
error: function (data) {
alert(data);
console.log(data);
}
});
}
Hope someone can tell me how to do it or hint me , thanks!
I am assuming that the data in the POST response is JSON.
As mentioned by #Kaushik you can use JSON.stringify(data) to convert the JSON data to a string.
First of all, I would recommend that you take a look at the content at the following link which explains JSON objects and how to work with them. JSON Objects - W3 Schools
For my examples, I have used https://jsonplaceholder.typicode.com/todos to return example JSON data.
If you wish to only access certain properties of the JSON object then you could accomplish this using the following code. Please bear in mind that the following code snippet assumes that the JSON object consists of a single record.
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/1',
dataType: 'json',
success: (data) => {
console.log('User ID: ' + data.userId);
console.log('Title: ' + data.title);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
If the JSON data consists of an array of JSON objects then you could approach this with the following code.
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos',
dataType: 'json',
success: (data) => {
data.forEach((record) => {
console.log('User ID: ' + record.userId);
console.log('Title: ' + record.title);
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
If you simply just want to display all JSON data as a string then the following code would accomplish this.
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/1',
dataType: 'json',
success: (data) => {
console.log(JSON.stringify(data));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Get ASP Page Method return from jQuery

I have an aspx page. I want to call the ASP.NET method via jquery. I have implemented the code but the problem is that I am getting the HTML of whole page rather than getting the returned string from ASP method. I need some assistance.
Here is my code:
[WebMethod]
public string PopulateData(string coursename)
{
return "called";
}
and here is the jquery method:
var subject = 'database';
$.ajax({
type: "POST",
url: "CourseDetail.aspx/PopulateData",
data: "{coursename:'" + subject + "'}",
success: function (msg) {
// Do something interesting here.
alert('result : ' + msg);
}
Add in the contentType and dataType.
var subject = 'database';
$.ajax({
type: "POST",
dataType: "text",
contentType: "application/json; charset=utf-8",
url: "CourseDetail.aspx/PopulateData",
data: "{coursename:'" + subject + "'}",
success: function (msg) {
// Do something interesting here.
alert('result : ' + msg);
}
contentType is the header sent to the server, specifying a particular format.
Example: I'm sending json or XML
dataType is telling jQuery what kind of response to expect.
Expecting JSON, or XML, or HTML, etc....

How to call webmethod in Asp.net C#

I want to call a web method in asp.net c# application using the following code
Jquery:
jQuery.ajax({
url: 'AddToCart.aspx/AddTo_Cart',
type: "POST",
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Code:
[System.Web.Services.WebMethod]
public static string AddTo_Cart(int quantity, int itemId)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
But it always call page_load. How can i fix it?
There are quite a few elements of the $.Ajax() that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine.
Script example:
$.ajax({
type: "POST",
url: '/Default.aspx/TestMethod',
data: '{message: "HAI" }',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
failure: function (response) {
alert(response.d);
}
});
WebMethod example:
[WebMethod]
public static string TestMethod(string message)
{
return "The message" + message;
}
This is a bit late, but I just stumbled on this problem, trying to resolve my own problem of this kind. I then realized that I had this line in the ajax post wrong:
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
It should be:
data: "{quantity : '" + total_qty + "',itemId: '" + itemId + "'}",
As well as the WebMethod to:
public static string AddTo_Cart(string quantity, string itemId)
And this resolved my problem.
Hope it may be of help to someone else as well.
Necro'ing this Question ;)
You need to change the data being sent as Stringified JSON, that way you can modularize the Ajax call into a single supportable function.
First Step: Extract data construction
/***
* This helper is used to call WebMethods from the page WebMethods.aspx
*
* #method - String value; the name of the Web Method to execute
* #data - JSON Object; the JSON structure data to pass, it will be Stringified
* before sending
* #beforeSend - Function(xhr, sett)
* #success - Function(data, status, xhr)
* #error - Function(xhr, status, err)
*/
function AddToCartAjax(method, data, beforeSend, success, error) {
$.ajax({
url: 'AddToCart.aspx/', + method,
data: JSON.stringify(data),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: beforeSend,
success: success,
error: error
})
}
Second Step: Generalize WebMethod
[WebMethod]
public static string AddTo_Cart ( object items ) {
var js = new JavaScriptSerializer();
var json = js.ConvertToType<Dictionary<string , int>>( items );
SpiritsShared.ShoppingCart.AddItem(json["itemId"], json["quantity"]);
return "Add";
}
Third Step: Call it where you need it
This can be called just about anywhere, JS-file, HTML-file, or Server-side construction.
var items = { "quantity": total_qty, "itemId": itemId };
AddToCartAjax("AddTo_Cart", items,
function (xhr, sett) { // #beforeSend
alert("Start!!!");
}, function (data, status, xhr) { // #success
alert("a");
}, function(xhr, status, err){ // #error
alert("Sorry!!!");
});
One problem here is that your method expects int values while you are passing string from ajax call. Try to change it to string and parse inside the webmethod if necessary :
[System.Web.Services.WebMethod]
public static string AddTo_Cart(string quantity, string itemId)
{
//parse parameters here
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
Edit : or Pass int parameters from ajax call.
I'm not sure why that isn't working, It works fine on my test. But here is an alternative technique that might help.
Instead of calling the method in the AJAX url, just use the page .aspx url, and add the method as a parameter in the data object. Then when it calls page_load, your data will be in the Request.Form variable.
jQuery
jQuery.ajax({
url: 'AddToCart.aspx',
type: "POST",
data: {
method: 'AddTo_Cart', quantity: total_qty, itemId: itemId
},
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Page Load:
if (!Page.IsPostBack)
{
if (Request.Form["method"] == "AddTo_Cart")
{
int q, id;
int.TryParse(Request.Form["quantity"], out q);
int.TryParse(Request.Form["itemId"], out id);
AddTo_Cart(q,id);
}
}
The problem is at [System.Web.Services.WebMethod], add [WebMethod(EnableSession = false)] and you could get rid of page life cycle, by default EnableSession is true in Page and making page to come in life though life cycle events..
Please refer below page for more details
http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx
you need to JSON.stringify the data parameter before sending it.
Here is your answer.
use
jquery.json-2.2.min.js
and
jquery-1.8.3.min.js
Javascript :
function CallAddToCart(eitemId, equantity) {
var itemId = Number(eitemId);
var quantity = equantity;
var dataValue = "{itemId:'" + itemId+ "', quantity :'"+ quantity "'}" ;
$.ajax({
url: "AddToCart.aspx/AddTo_Cart",
type: "POST",
dataType: "json",
data: dataValue,
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert("Success");
},
error: function () { alert(arguments[2]); }
});
}
and your C# web method should be
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string AddTo_Cart(int itemId, string quantity)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Item Added Successfully";
}
From any of the button click or any other html control event you can call to the javascript method with the parameter which in turn calls to the webmethod to get the value in json format.

asp.net json web service sending array error Cannot convert object of type 'System.String' to type 'System.Collections.Generic.List`1[System.String]'

I want to insert data from JavaScript to database using ajax and webservice,
I have some controls which by jQuery I get their values and make an array of their values.
When I send the array it causes this error:
Cannot convert object of type 'System.String' to type'System.Collections.Generic.List1[System.String]'
var variables = Array();
var i=0;
$('#Div_AdSubmition').find('.selectBox').each(function () {
variables[i] = $(this).find('.selected').find(".text").html();
i++;
});
$.ajax({
type: 'post',
data: "{ 'a':'" +variables + "'}",
dataType: 'json',
url: 'HomeWebService.asmx/insertAd',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("data : " + data.d);
}
});
This is the C# Code
[WebMethod]
public object insertAd(List<string> a)
{
return a;
}
You need to make your data parameter of the $.ajax call like this: JSON.stringify({'a': variables})
The JSON variable is not available in < IE8 so you'll want to include a JSON implementation like the one mentioned in the answer here
Also, you had an extra } in the success function.
So, in the future, if you want to add extra parameters to your data object passed to the web service, you'd construct it like so:
var someArr = ['el1', 'el2'];
JSON.stringify({
'param1': 1,
'param2': 'two'
'param3': someArr
// etc
});
JavaScript:
var variables = Array();
var i = 0;
$('#Div_AdSubmition').find('.selectBox').each(function () {
variables[i] = $(this).find('.selected').find(".text").html();
i++;
});
$.ajax({
type: 'post',
data: JSON.stringify({'a': variables}),
dataType: 'json',
url: 'HomeWebService.asmx/insertAd',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("data : " + data.d);
});
});
C#
[WebMethod]
public object insertAd(List<string> a)
{
return a;
}
data: Data to be sent to the server. It is converted to a query string, if not already a string. It’s appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting.
So, try to add a new parameter to your ajax call:
$.ajax({
type: 'post',
data: { 'a': variables }, // Notice some changes here
dataType: 'json',
traditional: true, // Your new parameter
url: 'HomeWebService.asmx/insertAd',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("data : " + data.d);
}
});
Try this way. Maybe you'll need to change the Web service method to expect an array instead of a List, but I'm not sure.
Try this
data: JSON.stringify({ 'a': variables }),

What is contentType and dataType and data in jQuery ajax Post?

I have just started to Learn the Json and binding data to Gridview using Json but I am not able to understand what is the contentType and dataType and data ?
I used the Following code............
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Gridview.aspx/BindDatatable",
data: "{}",
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#gvDetails").append("<tr><td>" + data.d[i].OfficeName + "</td><td>" + data.d[i].City + "</td><td>" + data.d[i].Country + "</td></tr>");
}
},
error: function (result) {
alert("Error");
}
});
});
</script>
The contentType referres to the mime content type that specifies the type of content set to the server. This could indentify FORM-Encoded, XML, JSON and a plethora of other content types. It helps the server to determine how to handle the content.
dataType helps JQuery with regards to how to handle the data. if specifying json then the returned data will be evaluated as json and data passed to the success handler will be an object instead of a string
The data property is used for data passed to The server. If you pass in an Object literal. JQuery will pass it either as part of the request body (if type is post) or as part of the query string (if type is get)
if we specify the data type as Json then the returned data will be evaluated as Json and data passed to the success handler will be an object instead of string,Lets see the example
$.ajax({
type: "POST",
url: "ProductWebService.asmx/GetProductDetails",
data: "{'productId':'" + productId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var Product = response.d;
$("#spnProductId").html(Product.Id);strong text
$("#spnProductName").html(Product.Name);
$("#spnPrice").html(Product.Price);
$("#outputTable").show();
},
failure: function (msg) {
alert(msg);
}
});

Categories

Resources