Click here to Skip to main content
15,921,210 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
me want to call a function which is on server with name testmeforcall().now i want to call that function locally on button click through javascript .how is it possible can any one give a simple idea or simple code.....plz...............help me out..
Posted

 
Share this answer
 
We have following methods for calling function .....

1. You can use the PageMethods to call server side function (C#) from ClientSide(Javascript)
Follow the blow steps
(a) Add a script Manager to your page and set the 'EnablePageMethods' property of script manager to True.

<asp:ScriptManager ID="ScriptManager2" runat="server" EnablePageMethods="true"/>

(b) Add Javascript function to the body section of page

JavaScript
<form id="form1" runat="server">
   <script type="text/javascript">
       function CallingServerSideFunction() {
           PageMethods.GetData();
       }
   </script>
   </form>


(c) Add the method you want to call in c#
C#
[System.Web.Services.WebMethod]
public static void GetData()
{
    MessageBox.Show("Calling From Client Side");
    //Your Logic comes here
}


(d) Call javascript function on any control of the page.
<input type="button" value="Submit" onclick="CallingServerSideFunction()" />

_____________________________________________________________________________
2. Call Server Side method from JavaScript in ASP.NET using JQuery ajax

script
JavaScript
<script type="text/javascript">
        function GetServerDate() {
            $.ajax({
                type: "post",
                url: "Default.aspx/GetServerDate",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    OnSuccess(result.d);
                },
                error: function (xhr, status, error) {
                    OnFailure(error);
                }
            });
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
                document.getElementById("currentDate").innerHTML = dateTime;
            }
        }
        function OnFailure(error) {
            alert(error);
        }

    </script>

C# or server side function
C#
protected void Page_Load(object sender, EventArgs e)
{

}

[System.Web.Services.WebMethod]
public static string GetServerDate()
{
    return DateTime.Now.ToLocalTime().ToString();
}


________________________________________________________________________________________________________
3. Call Server Side method from JavaScript using XMLHttpRequest with Ajax call(Asynchronously)

The XMLHttpRequest object is used to exchange data with a server behind the scenes. You can call server side C# web method from JavaScript client side by using this object without refreshing or reloading the page. Here, I have written example to get web server current Date Time by using XMLHttpRequest object with Ajax(Asynchronous) call.

script
JavaScript
<script type="text/javascript">
    function GetServerDate() {
        var xmlhttp;
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        var url = "Default.aspx?Method=GetServerDate";
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("currentDate").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("Get", url, true);
        xmlhttp.send();
    }

</script>


C# or server side code
C#
private void GetServerDate()
    {
        Response.Clear();
        Response.Write(DateTime.Now.ToString());
        Response.End();
    }

Note: Don't forgot to include the line Response.Cache.SetCacheability(HttpCacheability.NoCache) to stop page cache, otherwise you will get same result from cached page.
________________________________________________________________________________________________________
4. Call Server Side function from JavaScript using XMLHttpRequest without Ajax call(synchronously)


If you want to call web server C# function as Synchronous method (without Ajax call), you need to change value true to false in the line xmlhttp.open("Get", url, true);

JavaScript
<script type="text/javascript">
       function GetServerDate() {
           var xmlhttp;
           if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
               xmlhttp = new XMLHttpRequest();
           }
           else {// code for IE6, IE5
               xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
           }
           var url = "Default.aspx?Method=GetServerDate";
           xmlhttp.open("Get", url, false);
           xmlhttp.send(null);
           document.getElementById("currentDate").innerHTML = xmlhttp.responseText;
       }

   </script>



C# code

C#
private void GetServerDate()
   {
       Response.Clear();
       Response.Write(DateTime.Now.ToString());
       Response.End();
   }



_______________________________________________________________________________________________________________

5. By __doPostBack

Simply put a asp button on form. Set it display:none.


<asp:Button id="xyx" runat="server" style="display:none" OnClick="xyx_Click" />


On its click event call any server side event.
C#
protected void xyx_Click(o,e)
{
   //you server side statements
}


To call its from JavaScript use as below:

JavaScript
<script  type="text/javascript">

function myserverside_call()
{
var o = document.getElementById('<%=xyx.ClientID%>');
o.click();
}

function anyotherjsfunc()
{
   //some statements
   myserverside_call();
}
</script>





Following is some links for the help

http://www.morgantechspace.com/2014/01/Call-Server-Side-function-from-JavaScript-in-ASP-NET.html[^]
http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/calling-an-Asp-Net-C-Sharp-method-web-method-using-javascript/[^]

http://www.dreamincode.net/forums/topic/217965-calling-c%23-event-in-javascript/[^]
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900