2

I am trying to send some data to a generic handler and pass that information back in the response using jQuery.ajax(). For some reason, when I send the data up based on an answer to another question I found (.NET Simple Form Submit via AJAX and JQUERY), there is nothing in the context.Request object.

Here is my ajax call:

function retrieveStats(monster) {
    $.ajax({
        type: "POST",
        url: "MonsterRequests.ashx",
        data: { "monster": monster },
        contentType: "application/json; charset=utf-8",
        success: function (msg) {
            alert(msg.d);
        },
        error: function (jqXhr, status, errorThrown) {
            alert(errorThrown);
        }
    });
}

And here is the code for my handler:

public class MonsterRequests : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        string monsterName = context.Request["monster"];

        context.Response.ContentType = "text/plain";
        context.Response.Write("{\"d\":\"" + monsterName + "\"}");
    }

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

I am able to pull the information off by accessing the context.Request.InputStream and reading via a StreamReader, but I am curious as to why I can't just pull the info directly off of the request.

Any help with this would be greatly appreciated.

Community
  • 1
  • 1
Bic
  • 3,141
  • 18
  • 29

1 Answers1

2

Remove content type as you are not sending json. Try this.

var monster = "value";
    $.ajax({
        type: "POST",
        url: "MyHandler.ashx",
        data: { monster: monster },
        success: function(msg) {
            alert(msg.d);
        },
        error: function(jqXhr, status, errorThrown) {
            alert(errorThrown);
        }
    });
Priyank
  • 1,353
  • 9
  • 13
  • Removing the content type made it work when I send data: { "monster" : monster}. I am marking that as the answer. Why was it not considered json the way I had it. Also, I created and sent a JSON object (using $.parseJSON), but it still didn't show anything in the request. – Bic Dec 12 '13 at 00:43
  • By default contentType of $.ajax is 'application/x-www-form-urlencoded; charset=UTF-8' See Link: http://api.jquery.com/jQuery.ajax/ And The Form property is populated when the HTTP request Content-Type value is either "application/x-www-form-urlencoded" or "multipart/form-data". See Link: http://msdn.microsoft.com/en-us/library/system.web.httprequest.form(v=vs.110).aspx – Priyank Dec 12 '13 at 04:29
  • That explains it. Thanks again. :D – Bic Dec 12 '13 at 16:13