Call ASP.NET Handler (ASHX) using JavaScript

I was working on an application which used AJAX and needed the XMLHttpRequest object to communicate with an ASP.NET Generic Handler (.ashx), which contained some server-side logic. Here’s a working prototype if you have a similar requirement

We will first create an ASP.NET handler (ashx) which accepts a ‘Name’ parameter and greets the user by appending ‘Hello’ to it.

We will then call this ASP.NET Handler (ashx) via JavaScript by passing in a value entered in an ASP.NET TextBox.

ASP.NET Handler

Right click your ASP.NET Project > Add New Item > Generic Handler > call it SayHello.ashx. Add the following code:

<%@ 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>

In the code shown above, on the asp.net button click event, we call the callASHX() javascript function. In this function, we first initialize our XMLHttpRequest object by calling the XMLHttpRequest() function and asynchronously invoke an .ashx file called SayHello.ashx and pass the textbox value to it. If the request to the .ashx handler completes successfully, the XMLHttpRequestCompleted() function is invoked and the user is greeted.

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

8 comments:

niku said...

try using jquery??

Jonathan Wood said...

Is this book available in print?

Suprotim Agarwal said...

@niku: jQuery? Why? :)

@Jonathan Wood: Are you referring to this book - http://www.dotnetcurry.com/order/jQueryASPNETRecipesBook.aspx ? There is only an ebook version available.

Anonymous said...

Because with jquery you need much less code

Anonymous said...

isn't it necessary to register the httphandler in web.config????

crazy kittu said...

Hi , I am getting this type of error:

Microsoft JScript runtime error: Object doesn't support property or method 'open' .



Any Suggestions ?

Suprotim Agarwal said...

Does this happen on all browsers? Which browser are you using?

crazy kittu said...

i am doing in IE. In firefox no error msg is showing.....and not executing the handler.