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....
Related
I'm trying to call a server side method with ajax. This is what I've got:
Client side:
function accept(thisButton) {
$.ajax({
type: "POST",
url: "Default.aspx/editMaxUsers",
data: '{param: "' + $(thisButton).prev().val() + '" }',
contentType: "application/json: charset=utf-8",
dataType: "json",
success: function (result) { alert("successful" + result.d); }
});
}
Server side:
[System.Web.Services.WebMethod]
public static string editMaxUsers(string maxUsers)
{
return maxUsers; //I also have a breakpoint here that isn't stopping the execute
}
When I check the calls with firebug I can see that the POST is being sent and looks fine. But Nothing seems to be happening on server side. What am I doing wrong?
EDIT: Don't know if it's relevant, but the url already contains some parameters. I've tried the following url: "Default.aspx/" + window.location.search + "editMaxUsers" but no success.
The parameters of your WebMethod need to match the parameter name you are passing in.
Change
data: '{param: "' + $(thisButton).prev().val() + '" }',
to
data: '{maxUsers: "' + $(thisButton).prev().val() + '" }',
1.Go to App_Start/RouteConfig and change
settings.AutoRedirectMode = RedirectMode.Permanent;
to
settings.AutoRedirectMode = RedirectMode.Off;
2.As #F11 said the paramter in the WebMethod and the key in the json object should be with the same name and what I strongly recommend is not to build json object manually. It is better to do:
function accept(thisButton) {
var data = {};
data.maxUsers = $(thisButton).prev().val();
$.ajax({
type: "POST",
url: "Default.aspx/editMaxUsers",
data: JSON.stringify(data),
contentType: "application/json: charset=utf-8",
dataType: "json",
success: function (result) { alert("successful" + result.d); }
});
}
I'm using AJAX to populate some cascading combo box as shown in the next image:
When an option is selected in the combo box, it should populate the "Municipio" combo box, to do such a thing I invoke a method using AJAX called CargarCombos(int intAccion, string strCodigo), this method receives the next information:
But the problem resides when receiving the response from the AJAX method, it seems it's not invoking the method mentioned before and to top it all it just responds the same HTML source code that the page contains, has seen here:
If you guys can help me I would be totally grateful. Thanks.
EDIT:
Following the suggestions I'm adding the AJAX command and the WEBMethod:
AJAX:
$.ajax({
type: "POST",
url: pageUrl + '/CargarCombos',
data: '{intAccion: ' + $Accion + ', strCodigo: ' + JSON.stringify($ComboBox.val()) + ' }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
PopularControl(response.d, $control);
},
failure: function(response) {
alert(response.d);
}
});
WEBMEthod:
[WebMethod()]
public static ArrayList CargarCombos(int intAccion, string strCodigo)
{
ArrayList list = new ArrayList();
////LLamo a las variables necesarias.
BLL.cDirecciones DireccionesDAL = new BLL.cDirecciones();
Util.cFuncion oUtil = new Util.cFuncion();
DataSet oDataCombos = new DataSet();
oDataCombos = DireccionesDAL.CargarCombos(intAccion, strCodigo);
if (oDataCombos.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in oDataCombos.Tables[0].Rows)
{
list.Add(new ListItem(row.ItemArray[1].ToString(), row.ItemArray[0].ToString()));
}
}
return list;
}
From the screenshots, it seems you're using WebForms. If that's the case, is the method you are posting to instance or static? Because if it's not static, or the method isn't marked with the WebMethod attribute, this will happen. That's because your ajax request is just treated as a normal full postback.
e.g it should look like
[WebMethod]
//assuming MyModel is the name of your model class to send back to the client.
public static MyModel CargarCombos(int intAccion, string strCodigo)
{
//whatever it is you do here
}
If you're calling the WebMethod via JQuery, make sure that you're setting the content type to JSON e.g.
$.ajax({
type: "POST",
url: "Pendientes.aspx/CargarCombos",
data: "{intAccion:1, strCodigo:'BAR'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
});
I want to read data which is posted in JSON in my c#.net application? I am very new with this JSON and POST method?
Can anyone please help me?
I am posting data from page1. to other page2 (smsstaus.aspx in my case) for testing purspoe.
I want to read that JSON posted data in PageLoad of Page2.
Sample code.....
function SendSMSStatus() {
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx",
data: '{"SmsSid":"' + $("#<%= txtSmsSid.ClientID%>").val() + '","SmsStaus":"' + $("#<%= txtSmsStaus.ClientID%>").val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('update the db here');
},
error: function () { }
});
}
You could define a WebMethod in your smsstatus.aspx (SendStatus for example)
An implementation could look something like this (from the top of my head)
[WebMethod]
public static void SendStatus(string sid, string status)
{
// retrieve status
}
Now you can create a request to consume this method, like this:
function SendSMSStatus() {
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx/SendStatus",
data: '{"SmsSid":"' + $("#<%= txtSmsSid.ClientID%>").val() + '","SmsStaus":"' + $("#<%= txtSmsStaus.ClientID%>").val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('update the db here');
},
error: function () { }
});
.NET wil deserialize the json string to and pass them as arguments to SendStatus
when you are using Jquery and you throw JSON in the data thingy it will change in a normal Post but what you are now doing is gonna give problems change the code to:
function SendSMSStatus() {
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx",
data: {"SmsSid":$("#<%= txtSmsSid.ClientID%>").val(),"SmsStaus": $("#<%= txtSmsStaus.ClientID%>").val()},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('update the db here');
},
error: function () { }
});
}
and you can use the normal POST but if you want to play with JSON in C# see this aritcle
http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx
Do not change the contentType if you want to request the aspx (WebForm) and not the WebMethod. (When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded").
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx",
data: '{"SmsSid":"' + $("#<%= txtSmsSid.ClientID%>").val() + '","SmsStaus":"' + $("#<%= txtSmsStaus.ClientID%>").val() + '"}',
dataType: "json", // The type of data that you're expecting back from the server.
success: function (msg) {
alert(msg.d);
},
error: function () { }
});
Receive data from the Page_Load handler,
//Read Form data
string testData = Request["SmsSid"] + " " + Request["SmsStaus"];
//Prepare Json string - output
Response.Clear();
Response.ContentType = "application/json";
Response.Write("{ \"d\": \"" + testData +"\" }");
Response.Flush();
Response.End();
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);
}
});
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?