Search code examples
javascriptasp.netjsonxmlhttprequestresponse.write

How to handle jSON XMLHttpRequest response?


I'm trying to control the json response I send back to the client but didnt know exactly how.. Here is a simple demo:

js code

xhr = new XMLHttpRequest();
xhr.open("POST", "page.aspx", true);
xhr.send();

// handle the response with xhr.responseText

.cs code

    bool success = false;
    string message = String.Empty;

    // Create JSON Response
    var jsonData = new
    {
        success = success,
        message = message
    };

    Response.Write(jsonData);    

The problem is that when I look on the xhr.responseText I see:

"{ success = False, message = } 
<!DOCTYPE html PUBLIC ....
....
..
"

Solution

  • You want to do Response.Clear() and then Response.End() after writing the jsonData.

    Then you'll need to handle the JSON response in javascript. I recommend Crockford's JSON library.

    I also recommend using jQuery's $.ajax() function rather than hand-rolling your own XHR calls.

    PS. Ajax calls would be better made to either ASHX resources or PageMethods/WebMethods declared on your ASPX page. Better still, abandon webforms and use ASP.NET MVC with JsonResults returned from your Controller.

    PPS. If you do end up using WebMethods, this article is excellent.