Click here to Skip to main content
15,901,122 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do i call code behind file method using JQury..
following is my JQuery..
XML
 $(document).ready(function () {

            $("#btnRegister").click(function () {
                debugger;
                var username = $("input#txtUserName").val();
                var password = $("input#txtPassword").val();
                $.ajax({
                    type: 'POST',
                    url: '/RegisterUser',
                    data: { UserName:username, Password:password },
                    ContentType: 'application/Json',
                    dataType: "json",
                    success: function (data) {
                        alert("Register succesfully");
                    },
                    error: function () {
                        alert("Error while registration");
                    }
                });
            });
});

Following is the method i have written in default.aspx.cs file

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static void RegisterUser(string UserName, string Password)
{
    // code to insert in database
}</pre>
Posted

Use It:

XML
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>call server side method from javascript in asp.net</title>
<script type="text/javascript" language="javascript">
function callservermethod() {
var name = $get("txtName").value;
PageMethods.GetCurrentDate(name, OnSuccess, OnFailure);
}
function OnSuccess(result) {
if (result) {
alert(result);
}
}
function OnFailure(error) {

}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
Enter Name of Person: <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnClick" runat="server" Text="Click" OnClientClick ="callservermethod()" />
</div>
</form>
</body>
</html>




C#
[WebMethod]
public static string DisplayData()
{
return DateTime.Now.ToString();
}
 
Share this answer
 
 
Share this answer
 
XML
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "yourpage.aspx/yourmethod",
data: "{}",
dataType: "json",
success: function(data) {
//Write functionality to display data
},
error: function(result) {
alert("Error");
}


<pre lang="vb">This is the function declaration of JSON format we are using this JSON function to call web methods using JQuery $.ajax() whenever we need to make Ajax call with JQuery then we will use JSON functions like as we mentioned in above format. Here type, ContentType and dataType are same for all functions only url, data and success and error parameters will vary based on our requirement.

url: This is the path of our Webmethods

data: we will pass parameters using this parameter if no parameters then we need to use data: &quot;{}&quot;

success: Once our web method execution completed then success function will execute and return required data
error: This parameter is used to display required error message whenever we get problem.

(Note: JSON is a case sensitive please be careful before write JSON format of data</pre>


XML
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>JQuery Call asp.net page methods</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/DisplayData",
data: "{}",
dataType: "json",
success: function(data) {
$("#lbltxt").text(data.d);
},
error: function(result) {
alert("Error");
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<label id="lbltxt" runat="server"></label>
</form>
</body>
</html>



using System.Web.Services;

C#
[WebMethod]
public static string DisplayData()
{
return DateTime.Now.ToString();
}
 
Share this answer
 
Comments
Vishal.Shimpi144 5-Dec-12 23:48pm    
i have done it... but still the debbuger wont heat the method break point... it will simple alert me register successsfuly....
RahulRana723 5-Dec-12 23:53pm    
Because Your Method Register user Does Not return Any Value.Your Return type Is Void
Well this is wrong
data: { UserName:username, Password:password },

Should be something like this
var jData = "{" +
"\"m_firstName\" : \"" + txt_FirstName_enc + "\", " +
"\"m_lastName\" : \"" + txt_LastName_enc + "\", " +
"}";

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "connect.asmx/send_Connection",
  data: jData,
  dataType: "json",
  error: function (xhr, status, error) {

      exitCode = 2;
      alert(xhr.responseText);

  },
  success: function (responseText) {
    try {
      eval('(' + responseText.d + ')');
   }
   catch (err) {
   }

   var obj = jQuery.parseJSON(responseText.d);
   var exitCode = obj.exitCode;

And then your web service
With json_response
  .Append("{")
  .Append(" ""exitCode"" : " & exitCode.ToString)
  .Append("}")
End With

Dim js As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer
js.Serialize(json_response.ToString)

Return json_response.ToString


Well, since you gave us pieces of code, you get pieces back. Run the json data string through a validator before sending it, and run the web service json response string through a validator to make sure it's good.

Google json validator
 
Share this answer
 
Change Your Url.Give Url With Page name.If You Satisfy Then Msg me

C#
$(document).ready(function () {

            $("#btnRegister").click(function () {
                debugger;
                var username = $("input#txtUserName").val();
                var password = $("input#txtPassword").val();
                $.ajax({
                    type: 'POST',
                    url: 'Default.aspx/RegisterUser',
                    data: { UserName:username, Password:password },
                    ContentType: 'application/Json',
                    dataType: "json",
                    success: function (data) {
                        alert("Register succesfully");
                    },
                    error: function () {
                        alert("Error while registration");
                    }
                });
            });
});

Following is the method i have written in default.aspx.cs file

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static void RegisterUser(string UserName, string Password)
{
    // code to insert in database
}</pre>
 
Share this answer
 
v2
Use It.Jquery Is Case Sensitive:Remember

$.ajax({
type: "POST",
url: "Default2.aspx/RegisterUser",
data: "{'UserName':'" + username + "'}",
contentType: 'application/json',
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function () {
alert("Error while registration");
}
});
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900