Click here to Skip to main content
15,867,704 members
Articles / Programming Languages / Javascript

Call HTTPhandler from jQuery, Pass Data and Retrieve in JSON Format

Rate me:
Please Sign up or sign in to vote.
4.85/5 (13 votes)
4 Jul 2011CPOL3 min read 112K   33   12
Call HTTPhandler from jQuery, Pass data and retrieve in JSON format

For the past few days, 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 it 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.

JavaScript
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:

JavaScript
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:

JavaScript
// 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:

C#
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:

C#
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:

C#
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:

JavaScript
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)


Written By
Software Developer (Senior)
India India
Brij is a 3-times Microsoft MVP in ASP.NET/IIS Category and a passionate .NET developer. More than 6 years of experience in IT field, currently serving a MNC as a Tech Lead/Architect.

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: Code Wala

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

Comments and Discussions

 
QuestionNice Pin
Member 1129740923-Feb-15 17:15
Member 1129740923-Feb-15 17:15 
QuestionThanks Pin
lajapathy arun17-May-12 21:00
lajapathy arun17-May-12 21:00 
AnswerRe: Thanks Pin
Brij18-May-12 3:38
mentorBrij18-May-12 3:38 
Questionis this an error? Pin
darkdusky21-Mar-12 3:22
darkdusky21-Mar-12 3:22 
is this line correct: context.Response.ContentType = "text/html";\

Is the backslash a typo? Also do the datatypes of the handler not have to match the call to the handler? The handler is using context.Response.ContentType = "text/html" but jquery uses:application/json
I have copied your code fairly closely. When I call the handler from the address bar I get:
{Id:MyID, Name:Test, myInt:999} (each inside speechmarks)
But in the jquery the OnComplete function is called but does not return results:
function OnComplete(result) {
alert([result.Id, result.Name]); //this fails
alert(result); this returns null
};

Ran Fiddler and when calling the handler in the address bar fiddler shows GET followed by the url and parameters, and and the output.
But when called from jquery Fiddler shows OPTIONS followed by the same url and parameters, and with no output.

modified 21-Mar-12 9:33am.

AnswerRe: is this an error? Pin
Brij21-Mar-12 3:32
mentorBrij21-Mar-12 3:32 
Questionfill gridview using jquery ajax httphandler Pin
codeben117-Nov-11 5:06
codeben117-Nov-11 5:06 
GeneralMy vote of 5 Pin
germ1311-Jul-11 20:04
germ1311-Jul-11 20:04 
GeneralRe: My vote of 5 Pin
Brij17-Nov-11 6:14
mentorBrij17-Nov-11 6:14 
GeneralNice Pin
Shahriar Iqbal Chowdhury/Galib5-Jul-11 11:24
professionalShahriar Iqbal Chowdhury/Galib5-Jul-11 11:24 
GeneralRe: Nice Pin
Brij5-Jul-11 18:07
mentorBrij5-Jul-11 18:07 
QuestionHave you tested this code ? Pin
winheart30-Jun-11 20:03
winheart30-Jun-11 20:03 
AnswerRe: Have you tested this code ? Pin
Brij4-Jul-11 7:20
mentorBrij4-Jul-11 7:20 

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

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