Call a code behind method using jQuery Ajax.

Problem:
Here we are interested in calling a code behind function which is present on some other page and we don’t want page to be refreshed or an apparent post back to happen. On of the possible way of doing this is jQuery Ajax.

Sample Code:

---------------------------Test.aspx-------------------------------- 

<script type="”text/javascript”">
    $(document).ready
    (
        function () 
        {
            var JSONObject = new Object; //Initialize a new JSON object as this is the most common mistake making a JSON object
            $(‘#btn’).click
            (
                function () 
                {
                    JSONObject.name = $(‘#lid’).val().toString(); //Read Data from a textbox with id = lid
                    JSONstring = JSON.stringify(JSONObject); //Stringyfy in JSON format
                    alert(JSONstring); //Alert to check your request you can remove later on
                    $.ajax
                    (
                        {
                            type: “POST”,
                            url: “Test1.aspx/GreetingMessage”, // Request Post to page Test1.aspx and calling method GreetingMessage
                            data: JSONstring, // Pass Request String
                            contentType: “application/json; charset=utf-8″,
                            dataType: “json”,
                            success: function (response) 
                                     {
                                           alert(response.d.toString());
                                     },
                             error: function (xhr, ajaxOptions, thrownError) 
                                     {
                                        alert(xhr.status);
                                        alert(thrownError);
                                     }
                          }
                     );
                }
            );
        }
    ); //close ready
</script>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:TextBox ID=”lid” runat=”server” Width=”200px”></asp:TextBox>
<asp:Button ID=”btn” runat=”server” Width=”200px” Text=”Post” /></div>
</form>
</body>
//Test.aspx functionality Ends here


---------------------------Test1.aspx.cs---------------------------- 

[System.Web.Services.WebMethod] //Required for ajax posting
public static string GreetingMessage(string name) //Method should be declared as static
{
     return “Hello ” + name + Environment.NewLine + “Welcome to world of jQuery Ajax”;
}



Happy Coding!!!

Comments

Popular posts from this blog

Azure - Manage Blob Storage - Part #7 - Add Metadata to an Existing Container using C#

Azure - Manage Blob Storage - Part #5 - Create Folder Structure and upload a file to folder using an Existing Container using C#

Algorithm - Breadth First Search(BFS) - Python(3)