Sunday, April 3, 2011

Call ASP.NET Handler (ASHX) by JavaScript

Call ASP.NET Handler (ASHX) using JavaScript


<%@ WebHandler Language="C#" Class="SayHello" %>
using System;
using System.Web;

public class SayHello : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        string param = context.Request.Params["Name"];
        context.Response.Write("Hello, " + param);
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}
JavaScript Code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Call ASHX in JavaScript by DevCurry.com</title>
<script type="text/javascript">
    var httpReq = null;
    function callASHX() {
        httpReq = XMLHttpRequest();
        httpReq.onreadystatechange = XMLHttpRequestCompleted;
        httpReq.open("GET", "SayHello.ashx?Name=" +
            document.getElementById('<%=txtName.ClientID%>').value, true);
        httpReq.send(null);
    }

    // initialize XMLHttpRequest object
    function XMLHttpRequest() {
        var xmlHttp;
        try {
            // Opera 8.0+, Firefox, Safari
            xmlHttp = new XMLHttpRequest();
        }
        catch (e) {
            // IEBrowsers
            try {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {
                    return false;
                }
            }
        }
        return xmlHttp;
    }

    function XMLHttpRequestCompleted()
    {
        if (httpReq.readyState == 4)
        {
            try
            {
                alert(httpReq.responseText);
            }
            catch (e)
            {
            }
        }
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
       <asp:Button ID="btnCall" runat="server" Text="Enter Text and Click"
            OnClientClick="callASHX();"/>
    </div>
    </form>
</body>
</html>

No comments:

Post a Comment