Reputation: 2199
I am creating one .net application. And i simply wants to get this "Hi" string in my ajax call. What i need to do? Now i am getting as undefined all the time. Nothing else.
My client side script looks like blow
<script type = "text/javascript">
$(document).ready(function () {
$('.cart').click(function () {
var id = $(this).attr('id');
CallAddCart(id);
});
});
function CallAddCart(ItemId) {
$.ajax({
type: "POST",
url: "SearchParts.aspx/AddShopCart",
data: '{ItemId: "' + ItemId + '"}',
contenttype: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
OnSuccess(data);
},
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert('On sucess' + response);
alert(response);
}
</script>
And my server side looks like
[WebMethod()]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string AddShopCart(string ItemId)
{
return "Hi";
}
UPDATE:
The issue solved
That was one small mistake that caused these issues. The problem was with "contenttype" and "datatype". The both type's "t" which should be in capital letters. ie "contentType" and "dataType" :) now its able to get the Hi :)
Upvotes: 0
Views: 3591
Reputation: 2199
Case sensitive which caused the issue. In below script i updated with the correct usage
Previuosly it was "contenttype" and "datatype". Now changed to contentType and dataType
<script type = "text/javascript">
$(document).ready(function () {
$('.cart').click(function () {
var id = $(this).attr('id');
CallAddCart(id);
});
});
function CallAddCart(ItemId) {
$.ajax({
type: "POST",
url: "SearchParts.aspx/AddShopCart",
data: '{ItemId: "' + ItemId + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
OnSuccess(data);
},
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert('On sucess' + response);
alert(response);
}
</script>
Upvotes: 0
Reputation: 68
[WebMethod]
public static string AddShopCart(string ItemId)
{
return "Hi";
}
Remove it. [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
In Javascript
success: function (data) {
OnSuccess(data.d);
}
Credit: http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx
Upvotes: 2
Reputation: 68
I'll suggest to return value in JSON type
[WebMethod()]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string AddShopCart(string ItemId)
{
var result = new { d = "Hi" };
return JsonConvert.SerializeObject(result);
}
In Javascript
success: function (data) {
OnSuccess(data.d);
}
Upvotes: 3