Javascript loop calling code behind

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kenan
    New Member
    • Sep 2011
    • 2

    Javascript loop calling code behind

    hi, i have found a solution to calling code behind function but it does not work if i put the call statement in a loop

    Javascript
    Code:
    <script language="javascript">
    function init()
    {
    alert('hello ');
    <%SetData();%>; //------------------------------> main line
    alert('<%=strName%>');
    }
    </script>
    C#
    Code:
    private void Page_Load(object sender, System.EventArgs e)
    {
    if (!IsPostBack)
    {
    this.ImageButton1.Attributes.Add("onclick",
    "javascript:init();");
    }
    }
    public void SetData()
    {
    strName = "mainpico";
    }
    if i put the <%SetData();% >; in a loop it only executes once.....please help
    Last edited by Niheel; Sep 29 '11, 03:23 PM.
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Server side code can only run on the server. Javascript, a client side language, can not call a server side function. What you think of javascript calling the server side function is nothing of the sort. It's not being called by the javascript function, it's being evaluated at the server and then sending the page along to the client. If you look at the source code from the resulting page in a web browser, that server side code won't be there.

    Comment

    • kenan
      New Member
      • Sep 2011
      • 2

      #3
      thanks for the reply rabbit, Im not so clued up with this...still studying, is there anyway 2 call a c# code behind function from javascript...

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        You can use an XMLHTTPRequest to call a server side code page. Once the server has processed the code, it will call back to the client with the processed page. You then use the call back function to pull whatever data you need out of the result. The whole process is called AJAX.

        A simple example of that would be
        Code:
        function ajaxExample() {
        	var xmlhttp;
          xmlhttp=new XMLHttpRequest();
          
        	xmlhttp.onreadystatechange=function() {
        		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        			document.getElementById("someID").innerHTML=xmlhttp.responseText;
            }
          }
          
        	xmlhttp.open("GET","ajax.asp?q="+str,true);
        	xmlhttp.send();
        }

        Comment

        Working...