Showing posts with label jquery post. Show all posts
Showing posts with label jquery post. Show all posts

Friday, July 20, 2012

How to call .ashx file through jquery



your aspx page.
add the latest jquery into the head section

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

<script>
//document ready
$(function(){
$.ajax({
            type: "POST",
            url: "handler.ashx",
            data: { firstName: 'Rahul', lastName: 'Kumar' },
            // DO NOT SET CONTENT TYPE to json
            // contentType: "application/json; charset=utf-8",
            // DataType needs to stay, otherwise the response object
            // will be treated as a single string
            dataType: "json",
            success: function (response) {
                alert(response.d);
            }
        });
});
</script>

your handler.ashx file

    using System;
    using System.Web;
    using Newtonsoft.Json;

    public class Handler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string myName = context.Request.Form["firstName"];

            // simulate Microsoft XSS protection
            var wrapper = new { d = myName };
            // in order to use JsonConvert you have to download the
            // Newtonsoft.Json dll from here  http://json.codeplex.com/
            context.Response.Write(JsonConvert.SerializeObject(wrapper));
        }

        public bool IsReusable
        {
           get
           {
                return false;
           }
        }
    }