ASP.NET AJAX simple application using XMLHttpRequest

18,897

Solution 1

In your question you mentioned a XMLHttpRequestModule that you included through the script tag: <script type="text/javascript" src="XMLHttpRuquestModule.htm"></script>. XMLHttpRuquestModule.htm has spelling error in it ('Ruquest' instead of 'Request'), maybe that is causing your error.

Also note that including an htm file in the script will only work if there is JavaScript in that file and no actual html.

EDIT:

This is with reference to our exchange in the comments section.

I have managed to get hold of a ASP.NET server, ran the Ajax code against an ASPX page exactly like yours and everything is still okay. The alert box is still popping the correct response.

The difference is that, as originally suggested, I have renamed your XMLHttpRuquestModule.htm to XMLHttpRuquestModule.js and removed all markup from within it.

I am copying all the code here, try pasting it exactly and then running it:

HTML File(testXhr.htm):

<html>
    <head>
    <title></title>
    <script type="text/javascript" src="XMLHttpRequestModule.js"></script>
    <script type="text/javascript">

        function helloToServer() {
            var params = "name=" + encodeURIComponent(document.form.name.value);
            sendRequest("Default.aspx", params, helloFromServer, "POST");
        }

        function helloFromServer() {
            if (httpRequest.readyState == 4) {
                if (httpRequest.status == 200) {
                    alert("Response: " + httpRequest.responseText);
                }
            }
        }

    </script>
    </head>
    <body>
        <form name ="form" runat="server">
            <input type="text" name="name" />
            <input type="button" value="enter" onclick="helloToServer()" />
        </form>
    </body>
</html>

JavaScript File(XMLHttpRequestModule.js):

var httpRequest = null;

function getXMLHttpRequest() {
    if (window.ActiveXObject) {
        try {
            return new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                return new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e1) {
                return null;
            }
        }
    } else if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else {
        return null;
    }
}

function sendRequest(url, params, callback, method) {
    httpRequest = getXMLHttpRequest();
    var httpMethod = method ? method : 'GET';
    if (httpMethod != 'GET' && httpMethod != 'POST') {
        httpMethod = 'GET';
    }
    var httpParams = (params == null || params == '') ? null : params;
    var httpUrl = url;
    if (httpMethod == 'GET' && httpParams != null) {
        httpUrl = httpUrl + "?" + httpParams;
    }
    httpRequest.open(httpMethod, httpUrl, true);
    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    httpRequest.onreadystatechange = callback;
    httpRequest.send(httpMethod == 'POST' ? httpParams : null);
}

Solution 2

There are many issue using XMLHttpRequest directly. one of them is cross browser compatibility.. you should try using jQuery to create ajax calls. and you can create WebMethods is ASP.Net page to be called from javascript. have a look at them

Using jQuery for AJAX with ASP.NET Webforms

http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

EDIT:

In you want to use pure Javascript try

http://lamahashim.blogspot.com/2010/03/accessing-aspnet-webmethod-from.html

http://msdn.microsoft.com/en-us/library/ms535874%28v=vs.85%29.aspx

Share:
18,897
Si Young Kim
Author by

Si Young Kim

Updated on June 16, 2022

Comments

  • Si Young Kim
    Si Young Kim almost 2 years

    I am a newbie to ASP.NET and Ajax. I am trying to implement a sample application that updates web form without Postback. On click, my application sends request to its server using XMLHttpRequestModule and shows the data received through an alert window.

    I think the problem might be that default.aspx.cs page is not giving the httpRequest.responseText to its webform.

    cf. sendRequest method is in XMLHttpRequestModule to check the compatibility with browsers and send a request using the specified parameters and methods.

    Any help is much appreciated.

    Default.aspx

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title></title>
    <script type="text/javascript" src="XMLHttpRuquestModule.htm"></script>
    <script type="text/javascript">
    
        function helloToServer() {
            var params = "name=" + encodeURIComponent(document.form.name.value);
            sendRequest("Default.aspx", params, helloFromServer, "POST");
        }
    
        function helloFromServer() {
            if (httpRequest.readyState == 4) {
                if (httpRequest.status == 200) {
                    alert("Response: " + httpRequest.responseText);
                }
            }
        }
    
    </script>
    </head>
    <body>
    <form name ="form" runat="server">
    <input type="text" name="name" />
    <input type="button" value="enter" onclick="helloToServer()" />
    </form>
    </body>
    </html>
    

    Default.aspx.cs

    public partial class _Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
        String name = Request["name"];
        Response.Write(name);
        return;
    }
    }
    

    XMLHttpRequestModule

    <head>
    <title></title>
    <script type="text/javascript">
        var httpRequest = null;
    
        function getXMLHttpRequest() {
            if (window.ActiveXObject) {
                try {
                    return new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                    try {
                        return new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e1) {
                        return null;
                    }
                }
            } else if (window.XMLHttpRequest) {
                return new XMLHttpRequest();
            } else {
                return null;
            }
        }
    
        function sendRequest(url, params, callback, method) {
            httpRequest = getXMLHttpRequest();
            var httpMethod = method ? method : 'GET';
            if (httpMethod != 'GET' && httpMethod != 'POST') {
                httpMethod = 'GET';
            }
            var httpParams = (params == null || params == '') ? null : params;
            var httpUrl = url;
            if (httpMethod == 'GET' && httpParams != null) {
                httpUrl = httpUrl + "?" + httpParams;
            }
            httpRequest.open(httpMethod, httpUrl, true);
            httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            httpRequest.onreadystatechange = callback;
            httpRequest.send(httpMethod == 'POST' ? httpParams : null);
        }
    
    </script>
    </head>
    
  • Si Young Kim
    Si Young Kim over 12 years
    Thanks for your comment, but I'd like to try using XMLHttpRequest just to learn how it works. Also, I think I have already solved some compatibility issues using if-catch statement in my XMLHttpRequest module.
  • Shoaib Shaikh
    Shoaib Shaikh over 12 years
    you are right you can create your own logic to handle with cross browser issues.
  • Si Young Kim
    Si Young Kim over 12 years
    Thanks for pointing out the mistake! The code is still not working though:( The htm file only has JavaScript code in its head.
  • jpf
    jpf over 12 years
    You are welcome. What do you mean by 'in its head'? The src attribute expects a text file with no markup in it at all. Also, why are you using a .htm file instead of a .js.
  • Si Young Kim
    Si Young Kim over 12 years
    You are right. I should have used .js without any tag! The cod is sill not working though:(
  • jpf
    jpf over 12 years
    I don't have ASP.NET on my machine right now but I can confirm your JavaScript is fine. I copy-pasted your HTML and JavaScript code and ran it against a 2-line PHP script and got the alert box popping with the correct response. There is unlikely to be an error in your ASP.NET code but you can check it by typing 'yourservername/Default.aspx?name=myname'. If it prints your name, then the server-side component is fine too.
  • jpf
    jpf over 12 years
    The only thing I did differently was rename 'XMLHttpRuquestModule.htm' to 'XMLHttpRequestModule.js' and made sure that 'XMLHttpRequestModule.js' contains only JavaScript and no HTML.
  • Si Young Kim
    Si Young Kim over 12 years
    I tested my ASP.NET code as you have instructed and also corrected my js file names, but still see no alert boxes popping. I presume it probably has something to do with ASP.NET codes but still cannot figure it out. Thanks for your time and effort for helping me though!
  • Si Young Kim
    Si Young Kim over 12 years
    Thanks for your help. Now I see the alert box popping out. However, for some reason, the box contains the whole html of the page. Do you see it when you test my app and if so is there any way to remove it?
  • jpf
    jpf over 12 years
    I only see "Response: myname" where "myname" is what I entered on the form. If there is HTML in your ASPX page, that will get sent back to you. Use Response.End() instead of return in your Default.aspx.cs file.
  • jpf
    jpf over 12 years
    You are welcome :). If you like the solution, please consider upvoting my answer.
  • Si Young Kim
    Si Young Kim over 12 years
    I will as soon as I get 15 reputation:D