Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

How to Call Server Side Function with JavaScript

4.30/5 (7 votes)
20 Oct 2014CPOL2 min read 91.8K  
How to call server side function with JavaScript

In this article, you will find how we can call Server side static function using JavaScript and get value from it. Many times, developers find such requirement of fetching some data from Server side. Here is the code, where page will not follow Page life cycle and no data will be posted on the Server. Hence, code will be executed directly and rendered using Client side code.

Here is the aspx code

Image 1

We can use this code to bind dropdown or to show data in any control, in which we can display text data. The EnablePageMethods property of the ScriptManager Control must be set to true, it indicates whether public static page methods in an ASP.NET page can be called from a client script. Put “return false;“, if you are using web control instead of HTML control. This is will avoid postback on calling an event.

Script: keep this in head tag

Image 2

In the above code, On_Success and On_Failure are client side functions called after executing Server side function (GetNameServer). One of the best things which I like in AJAX is PageMethod. PageMethod by which one can expose server side page’s method in JavaScript. This brings so many opportunities, we can perform lots of operations without using slow and annoying post backs.

Server side code

Image 3

[WebMethod]” attribute to a server-side method is to make the method callable from remote Web clients. This is the “static” function that will be called directly from JavaScript and will return a string value. It cannot interact with the instance properties and methods of Page class, but can do so with other static properties and methods of the Page class.

We have used Server side method with no input parameter; we can pass input parameters as follows:

Client side code

Image 4

Server side code

Image 5

Script

Image 6

The above code will allow to pass input parameters and pass it to the Server side method.

 

Try this! J

Filed under: ASP.NET, CodeProject, Javascript Tagged: Calling c# code with JavaScript, Calling Server side method using JavaScript Image 7 Image 8 Image 9 Image 10 Image 11 Image 12 Image 13 Image 14

License

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