Friday 24 July 2009

How to call a Server Side Function from Client Side Code using JavaScript in Ajax

You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX. ASP.Net AJAX introduced a technique called PageMethods using which we can call server side methods from JavaScript. Try to imagine a scenario, in a user registration form, when user type a user name in a textbox, a server side process is triggered to find whether this is an exiting user or not in our user table in the database. In this example I am using the SQL Server 2005 as backend.

1.Create a demo table on Northwind db and insert 3 users into the table.

CREATE TABLE demo(user_id varchar(10) PRIMARY KEY);
insert into demo values ('user1');
insert into demo values ('user2');
insert into demo values ('user3');

2.Every server-side method that is called from the client-side, must be declared as “static”, and also has to be decorated with the [System.Web.Services.WebMethod] tag. Let’s create a simple function as below:

public static bool IsUserExist(string strUserID)
bool blUserExist = false;
string connectionString = "Data Source=localhost;Initial Catalog=Northwind; " +
"Integrated Security=True";
SqlConnection conn = new SqlConnection(connectionString);
string strSqlStatement = "select * from demo where user_id = '" + strUserID + "'";
SqlCommand cmd = new SqlCommand(strSqlStatement, conn);
SqlDataReader reader = cmd.ExecuteReader();

if (reader.HasRows)
blUserExist = true;


return blUserExist;

3. Go to the Markup page and drag a ScriptManager to the page. The “EnablePageMethods” attribute has to be added on the ScriptManager tag and set it to “true”.

4. Adding a simple HTML TextBox as:

5. Adding the JavaScript code as below:

The “OnSuccess” is the name of the JavaScript function that will be called if the request is successful. Whereas the “OnFailure” will be called if an exception is thrown.

6. Running the application. Will see the screenshot as below:

No comments:

Post a Comment