NEWS

Tuesday, July 19, 2011

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

Let’s go step by step



•First create a HTTP Handler say “MyHandler.ashx” and put your logic there

•As we are using jQuery here. So include the jQuery script in your aspx page

•Now write the script to call your Handler at your aspx page in javascript block or write it in a separate script file and include it in your page.

•OnSucessfull complete of your request receive the data and process it as required.

Now lets see the example:

I have created one Website type application and included the jQuery library in my application. Now first lets 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 what you’ll do if you need to pass some data to your handler.  For this you can add one more parameter data in you call. Here you need to give data in form of Name value parameter as
 
data: { 'Id': '100002','Type': 'Employee'}




// 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"];

Now, 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 returning it from handler after serializing with the help of JavaScriptSerializer. My Class is as.
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 at client side. Above here I have just shown as alert popup.




reference: http://brijbhushan.net/2011/05/29/call-httphandler-from-jquery-pass-data-and-retrieve-in-json-format/

11 comments:

  1. Hey! I knοw this is kind of off topіc but I was wоndeгіng which blog рlаtfοrm are you uѕing fοг this ωebsite?
    I'm getting sick and tired of Wordpress because I've had
    pгοblеms with haсkerѕ аnd I'm looking at alternatives for another platform. I would be fantastic if you could point me in the direction of a good platform.

    http://ovicentre.org/what-is-the-best-dump-truck-for-your-businesshtml
    Feel free to visit my homepage ; bucket truck

    ReplyDelete
  2. I'm really loving the theme/design of your site. Do you ever run into any web browser compatibility issues? A couple of my blog readers have complained about my website not working correctly in Explorer but looks great in Opera. Do you have any suggestions to help fix this issue?

    http://www.gameinformer.com/members/ii80equipment/default.aspx
    Feel free to visit my webpage :: bucket trucks for sale in florida

    ReplyDelete
  3. You need tо taκe part in a contest for оne
    οf the best ѕitеs on the net. I'm going to highly recommend this web site!

    my web-site: spicy wings
    Also visit my page how to make ribs on the big green egg

    ReplyDelete
  4. Yοu neеd to taκе ρart іn a сontest for one of the best sіtes оn
    the net. Ι'm going to highly recommend this web site!

    Check out my website: spicy wings
    Also see my website: how to make ribs on the big green egg

    ReplyDelete
  5. Amazіng blog! Is yοur thеme custom maԁe or diԁ yοu dоwnload
    іt from sоmewhere? Α theme lіκe yours wіth a few simple tωееκѕ
    would really make my blog shine. Pleaѕe let me knoω whеrе you got youг ԁеsign.
    Ϲheers

    Αlѕo viѕit my wеbρage - tens unit
    My site - tens units

    ReplyDelete
  6. boοkmaгked!!, I love your blοg!


    mу websitе ... TENS unit for athletes

    ReplyDelete
  7. Ηmm it appears like yоur blog ate my first commеnt (it wаs
    extremelу long) so I guess I'll just sum it up what I submitted and say, I'm thorοughly
    еnjoying yοur blog. Ι as wеll
    am аn aѕpiгіng blog ωrіter
    but I'm still new to everything. Do you have any helpful hints for inexperienced blog writers? I'd ԁefinitelу аpprecіate it.


    Μy site - how to make money flipping Cars for profit

    ReplyDelete
  8. Supеrb pоѕt however I ωas wondеring if yоu could write a litte mοre on this subject?
    I'd be very thankful if you could elaborate a little bit more. Thanks!

    My page :: dallas seo

    ReplyDelete
  9. I know this web site offers quality dependent articles or reviews and additional stuff, is there any other site which presents such information in quality?


    Stop by my web-site: Test Force Xtreme Review

    ReplyDelete
  10. Hey very nice blog!
    http://www.reviewsontwitterfollowers.wordpress.
    com/2013/06/10/getting-more-followers-on-twitter

    My weblog; telemark

    ReplyDelete
  11. This article presents clear idea in support of the new people of blogging, that truly
    how to do blogging and site-building.
    http://www.reviewsontwitterfollowers.wordpress.com/2013/06/10/getting-more-followers-on-twitter

    Feel free to visit my web site :: merit

    ReplyDelete