Click here to Skip to main content
Click here to Skip to main content

Call HTTPhandler from jQuery, Pass data and retrieve in JSON format

By , 4 Jul 2011
Rate this:
Please Sign up or sign in to vote.

Download Sample.zip - 50.26 KB 

For the last few days ago, I was working with HTTP handler. Here I was required to call handler from Client script. Later I found that I needed to pass some data to handler and also receive some from it.

So I was searching if there is some way we can pass some data to handler in some format and can receive too.

Here I am going to share how we can call a HTTPHandler from jQuery and pass some data to handler and receive as well.

So let’s go step by step:

  • First create an HTTP Handler, say “MyHandler.ashx” and put your logic there.
  • As we are using jQuery here, include the jQuery script in your aspx page.
  • Now write the script to call your Handler in your aspx page in JavaScript block or write it in a separate script file and include it in your page.
  • On successful completion of your request, receive the data and process it as required.

Now let's see the example:

I have created one Website type application and included the jQuery library in my application. Now first let's see how to call HTTP handler.

function CallHandler() {
    $.ajax({
        url: "Handler/MyHandler.ashx",
        contentType: "application/json; charset=utf-8",
        success: OnComplete,
        error: OnFail
    });
    return false;
}

Here url is the url of your Handler. contentType defines the content of the request. On successful completion of the request, the OnComplete method will be called. If there is any error of the request, the OnFail will be called. The dummy methods are:

function OnComplete(result) {
    alert('Success');
}
function OnFail(result) {
    alert('Request failed');

}

Now we can call this CallHandler method from any event. For the demo, I have called this on a button click.

Now what will you do if you need to pass some data to your handler. For this, you can add one more parameter data in your call. Here, you need to give data in the form of Name value parameter as:

// Now the updated method as
function CallHandler() {
$.ajax({
url: "Handler/MyHandler.ashx",
contentType: "application/json; charset=utf-8",
data: { 'Id': '10000', 'Type': 'Employee' },
success: OnComplete,
error: OnFail
});
return false;
}

Now you can access the data in handler’s ProcessRequest method as:

 string Id = context.Request["Id"];
 string type = context.Request["Type"];

If you want to receive data from Handler at Client side, how will you move ahead? It’s very easy to return data in JSON format.
Here in my sample example, I have created one Class Employee and return it from handler after serializing with the help of JavaScriptSerializer. My class is as follows:

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Department { get; set; }
}

Now let’s see the handler part. I am sending the Id of employee from Client:

public class MyHandler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {

        var employee = GetData(Convert.ToInt32(context.Request["Id"]));

        //Do the operation as required

        JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
        string serEmployee = javaScriptSerializer.Serialize(employee);
        context.Response.ContentType = "text/html";\
        context.Response.Write(serEmployee);
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

    private Employee GetData(int Id)
    {
        var employee = new Employee();
        employee.Id = Id;
        employee.Name = "Brij";
        employee.Age = 27;
        employee.Department = "Research and Development";

        //Write your logic here

        return employee;
    }
}

Now the CallHandler method will be as:

function CallHandler() {
    $.ajax({
        url: "Handler/MyHandler.ashx",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: { 'Id': '10000' },
        responseType: "json",
        success: OnComplete,
        error: OnFail
    });
    return false;
}

function OnComplete(result) {
    alert([result.Id, result.Name, result.Age, result.Department]);
}
function OnFail(result) {
    alert('Request Failed');
}

Now you can receive the data and use it as per your requirement on the client side. Above here, I have just shown it as alert popup.

I think this post will help you a lot as this can be used in different scenarios. The classic example could be.
“In many situation, we get the task to upload files in our applications with lots of validations; it could be validations like file type, content size and some business validations as well. All these validations could not be handled on client side only. One approach could be HTTPHandler which we can use for seamless validations.”

Thanks a lot to all of you.

Cheers,
Brij


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Brij
Software Developer (Senior)
India India
Brij is a Microsoft MVP in ASP.NET/IIS Category and a passionate .NET developer. Having around 5 years of experience in IT field, currently serving a MNC as a Sr. developer.
 
He is a very passionate .NET developer and have expertise over Web technologies like ASP.NET 2.0/3.5/4.0, jQuery, JSON, Javascript, IIS and related technologies. He is also a Exchange Server (EWS) Specialist. He has great experience in design patterns and N-Tier Architecture.
 
He is also certified as Microsoft Certified Technologies Specialist-ASP.NET and Microsoft Certified Technologies Specialist-WCF in .NET 4.0. He has also received several awards at various forums and his various articles got listed as "Article of the day" at ASP.NET Microsoft Official Website www.asp.net.
 
He has done MCA from NIT Durgapur and completed his graduation from Lucknow University.
 
Learning new technologies and sharing knowledge excites him most. Blogging, solving problems at various forums, helping people, keeps him busy entire day.


Visit his Blog: Brij's arena of .NET
 
Area of Expertise :
C#, ASP.NET 2.0,3.5,4.0, AJAX, JQuery, JSON, XML, XSLT, ADO.Net, WCF, Active Directory, Exchange Server 2007 (EWS), Java script, Web Services ,Win services, DotnetNuke, WSS 3.0,Sharepoint Designer, SQL Server 2000/2005/2008
Follow on   Twitter

Comments and Discussions

 
Questionfill gridview using jquery ajax httphandler Pinmembercodeben117-Nov-11 5:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140421.2 | Last Updated 4 Jul 2011
Article Copyright 2011 by Brij
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid