Monday, 24 October 2016

How to call ASP.Net web method using JQuery AJAX

In normal ASP.NET web forms, if you want to send any data to server your web page will be refreshed i.e. will do a postback.
In some case, if you want to send data to the server without using any post back then in this case you have to use a web method at server side and that will be called from JQuery side.

How to implement ASP.Net web method using JQuery AJAX?

HTML Page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

    <title></title>
    <script src="js/jquery.min.js"></script>
    <script>
        function SubmitData() {

            var name = 'Ram';
            var gender = 'Male';
            var age = '30';           
          
            $.ajax({
                type: "POST",
                url: "ajaxcall.aspx/SaveData",
                data: '{"name":"' + name + '", "gender":"' + gender + '", "age":"' + age + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                beforeSend: function () {
                    $('#loader').show();
                },
                success: function (data) {
                   
                    alert(data.d);
                    $('#loader').hide();
                },
                error: function (msg) {
                    //alert('3');
                    msg = "There is an error";
                    alert(msg);
                    $('#loader').hide();
                }
            });

        }
    </script>
</head>
<body>
    <div id="loader" style="displaynone;">
        <img src="ajax-loader.gif" />
    </div>
    <a href="#" onclick="SubmitData();">Submit</a>
</body>
</html>

WebMethod written in aspx.cs page


 [WebMethod]

    public static string SaveData(string name, string gender, string age)
    {
        try
        {
             
            return "OK";
        }



        catch (Exception ex)
        {

            return ex.Message;
        }

        finally
        {

        }
    }

No comments:

Post a Comment

Dear Readers, Please post your valuable feedback in the comment section if you like this blog or if you have any suggestions. I would love to hear the same from you. Thanks