Calling ASP.Net WebMethod using jQuery AJAX

Jquery allow users to call server side code without any postback.
Follow below steps:

Create a table with below script:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[userTable](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](50) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO


Write stored procedure to save data into table:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE InsertData

@name varchar (50)
AS
BEGIN

SET NOCOUNT ON;
insert into [dbo].[userTable] (name) values(@name)
END
GO

AJAX Method to Call Web method

  function SaveData() {
            var name = document.getElementById('<%=txtName.ClientID %>').value;
           
            $.ajax({
                type: "POST",
                url: /MyFolder/MyAjaxPage.aspx/SubmitData",
                data: '{"name":"' + name + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    if (data.d == "success") {
                     alert('Your data has been submitted.');

                    }

                   
                },
                error: function () {
                    alert('Please Try again.');

                    return false;

                }
            });

        }

Web method

Declare below connection string within class.

 SqlConnection sqlConnection = new SqlConnection("database connection string");
        [WebMethod]
        public static string SubmitData(string name)
        {
          try
          {
                         SqlParameter[] prmUserReg = new SqlParameter[1];
                         prmUserReg[0] = new SqlParameter("@name", name); 
                           SqlCommand cmd = new SqlCommand("InsertData", sqlConnection);
            cmd.CommandType = CommandType.StoredProcedure;
            if (sqlConnection.State == ConnectionState.Closed)
            {
                sqlConnection.Open();
            }
            cmd.Parameters.AddRange(prmUserReg);
            cmd.ExecuteNonQuery();
            }

            catch (Exception ex)
            {

            }

            finally
            {

            }

            return message;
        }

Comments

Popular posts from this blog

CAML Query in SharePoint 2010

Calling REST APi from server side code - C#

All about SharePoint 2010 Content Type Hub

SharePoint Interview Questions and Answers