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?
click(function () { var name = $('#name'). val(); /// alert("The btn was clicked."); jQuery. ajax({ url: 'test. aspx/GetData', type: "POST", dataType: "json", // data: "{'name': '" + name + "'}", contentType: "application/json; charset=utf-8", success: function (data) { alert(JSON.
you need to JSON. stringify the data parameter before sending it. Show activity on this post. 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.
As the WebMethod is static, it cannot call one normal method of the Page class. If you want to call one method inside the WebMethod, you need to mark it as Static.
<asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="HandleIT(); return false;" /> </div>
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With