IsCallback with XMLHttpRequest object

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Leo Smith
    New Member
    • Mar 2007
    • 45

    #1

    IsCallback with XMLHttpRequest object

    How can I make a return from a standard XMLHttpRequest set the IsCallback on the server? Or how can I capture a result from a post in the OnLoad event, then return a string without having to go through the Rendor and PreRendor events? All I am trying to do is send a post to the server and return a result like the callback routines do without having to place the call on the callback stack.

    Thanks,
    Leo
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    Originally posted by Leo Smith
    How can I make a return from a standard XMLHttpRequest set the IsCallback on the server? Or how can I capture a result from a post in the OnLoad event, then return a string without having to go through the Rendor and PreRendor events? All I am trying to do is send a post to the server and return a result like the callback routines do without having to place the call on the callback stack.

    Thanks,
    Leo

    I don't understand your question.
    What are you trying to do?
    Do you mean IsPostBack?
    Usually you check the IsPostBack value in the PageLoad event.

    I don't know what you mean by returning without going through the Render events....if you want to be able to view anything your application does in a web browser you have to go through these.

    Please explain what it is you are trying to do (explain the problem you are trying to solve).

    -Frinny

    Comment

    • Leo Smith
      New Member
      • Mar 2007
      • 45

      #3
      What I am trying to do is the following code

      Code:
      var xmlRequest
      
      function CreateXMLHttpRequest()
      {
          try
          {   // Newer browsers such as Firefox, Opera and IE 7 use this object
              xmlRequest = new XMLHttpRequest();
          }
          catch(err)
          {   // This is what older versions of IE use (post IE 4)
              xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
          }
          
      }
      
      function MakeAjaxPost(strUrl, strVal)
      {
          if(xmlRequest == null)
              CreateXMLHttpRequest();
              
          if(xmlRequest != null)
          {
              xmlRequest.open('POST', strUrl, true);
              xmlRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
              xmlRequest.onreadystatechange = function() 
              {
                  if (xmlRequest.readyState == 4)
                  { 
                      if(xmlRequest.status == 200 || xmlRequest.status == 304)
                          ReturnRequestedByInfo(xmlRequest.responseText);
                      else
                          alert('Update Failed from \"MakeAjaxPost\".\n\n   Status: ' +
                              xmlRequest.statusText + ' (' + xmlRequest.status + ')');
                  }
              }
              xmlRequest.send('__EVENTTARGET=&__EVENTARGUMENT=&' + strVal);
          }
      }
      The problem here is that when it get to the server I see a string I can use to post a page, when all I want to do is return a string similar to any normal callback function. The callback function goes from Page.Load to Page.RaiseCallb ackEvent to Page.GetCallbac kResult to Page.Unload and returns a result string to a new function, thus bypassing the PreRendor and Rendor functions with a page as a response file and not a simple string. I want to emulate the callback without having to use the normal callback functions, which have a couple limitations and bugs that have ran across.

      The basic question is how can I post the data to the server and then return the desired results without having to postback to the server? IsCallback is the simplist way but the Page.IsCallback bit is read-only. If I can cancel everything at the Page.Load and still return a string, then I would be happy. I just don't want a webpage to return.

      Thanks,
      Leo

      Comment

      • Leo Smith
        New Member
        • Mar 2007
        • 45

        #4
        I came up with a work around (really nothing more than a hack) to make this work. It really isn't very elegant but it gets the job done. Here is the code.

        Client Side JavaScript
        Code:
        //  Setup to use AJAX requests
        // This is function allows for asynchronous communication with server side
        // routines.  This allows for client side updates that will not require postbacks 
        // to the server.  
        var xmlRequest
        
        function CreateXMLHttpRequest()
        {
            try
            {   // Newer browsers such as Firefox, Opera and IE 7 use this object
                xmlRequest = new XMLHttpRequest();
            }
            catch(err)
            {   // This is what older versions of IE use (post IE 4)
                xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }
            
        }
        
        //  Used to make the call using Post method
        //  strUrl - URL for page to launch
        //  strVal - Value to be sent to the server (string value only)
        //  retFunc - Name of function to return to from the server.
        //  retFunc - Name of function to return if there is an error
        //
        //  NOTE:  On functions, don't use the "()" when passing the names
        function MakeAjaxPost(strUrl, strVal, retFunc, retError)
        {
            if(xmlRequest == null)
                CreateXMLHttpRequest();
                
            if(xmlRequest != null)
            {
                xmlRequest.open('POST', strUrl, true);
                xmlRequest.setRequestHeader('Content-Type', 
                                   'application/x-www-form-urlencoded');
                xmlRequest.onreadystatechange = function() 
                {
                    if (xmlRequest.readyState == 4)
                    { 
                        if(xmlRequest.status == 200 || xmlRequest.status == 304)
                            retFunc(xmlRequest.responseText);
                        else
                        {
                            if(retError == null)
                                alert('Update Failed from \"MakeAjaxPost\".\n\n   Status: ' +
                                        xmlRequest.statusText + ' (' + xmlRequest.status + ')');
                            else
                                retError(xmlRequest.responseText);
                        }
                    }
                }
                xmlRequest.send('__AJAXCALLBACK=&__AJAXSTRING=' + strVal);
            }
        }
        Server Side Code (in page class)
        Code:
            private string eventArgument = "";  // Used in GetCallbackResult() for 
                                           // processing original request
            private bool bIsXmlHttpRequest = false;
        
            protected void Page_Load(object sender, EventArgs e)
            {
                if ((string)Request["__AJAXCALLBACK"] != null)
                {
                    string s = (string)Request["__AJAXSTRING"];
                    if (s != null)
                        eventArgument = s;
                    else
                        eventArgument = "";
        
                    bIsXmlHttpRequest = true;
                }
                else
                    bIsXmlHttpRequest = false;
            }
        
            protected override void OnPreRender(EventArgs e)
            {
                if (bIsXmlHttpRequest != true)
                {
                    base.OnPreRender(e);
                }
            }
        
            protected override void Render(HtmlTextWriter writer)
            {
                if (bIsXmlHttpRequest == true)
                               // Must return string for write to work
                    writer.Write(GetCallbackResult()); // Standard Callback Function but
                               // can be any other function that returns a string and uses
                               // the eventArgument variable
                else
                    base.Render(writer);
            }
        Here is code I used to set this up and test this.
        Code:
        // Sever-Side 
        // Added in a setup function for page
        ctrl.Attributes.Add("onchange", "GetComboUpdate(this);");
        
        // This function is needed if using ICallbackEventHandler and regular ASP.NET
        // Callbacks
        public string GetCallbackResult()
        {
            int iFlag = 0;
            string result = "succeeded<~>";
        
            string[] sTok = { "||" };
            string[] sSplit = eventArgument.Split(sTok, 
                                     StringSplitOptions.RemoveEmptyEntries);
            // Attempt to convert the string into an int for switch statement
            if (int.TryParse(sSplit[0], out iFlag) == true)
            {
                if (IsUserValid() == true)      // Internal user validation
                {
                    switch (iFlag)
                    {
                        case 130:
                            if(sSplit.Length == 3)
                                result += eventArgument;  // Process function here for arg
                            break;
        
                        default:
                            result = "true";
                            break;
                    }
                }
                else  // Not a valid user anymore so need to start validation process
                {
                    result = "failed<~>" + eventArgument;
                }
            }
            return result;
        }
        
        
        
        // Client Script
        function GetComboUpdate(cb)
        {
            // values to parse and pass for processing
            var sVal = '130||' + cb.id + '||' + cb.options[cb.selectedIndex].value;
            MakeAjaxPost('test.aspx', sVal, ReturnComboUpdate);
        }
        function ReturnComboUpdate(rtnVal)
        {
            alert('Made it back:\n\n' + rtnVal);
        }
        Probably not very intuitive or even best practice. If there is something better I would be open to other solutions. You will note that context is missing, but it could probably be handled if necessary by extending the retFunc, and retError functions for the value.

        Leo
        Last edited by Leo Smith; Jun 28 '07, 12:32 PM. Reason: Acidently hit submit before I was ready.

        Comment

        Working...