AlexAlezzo AlexAlezzo - 19 days ago 5
Ajax Question

ASP.NET receive and respond to AJAX request

So I'm trying to setup ajax-exchange between a JavaScript frontend and ASP.NET backend. I've stumbled upon this example from w3schools:

function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
}


However, it's unclear to me how to handle this request on server side. What should my demo_get2.asp look like to process this request?

Answer

In Asp.NET, you can do this by clearing all the headers and response built so far by the framework then adding your custom data and header and flushing out the response without any other additional framework methods to be called (like, prerender, render methods) as below.

protected void Page_Load(object sender, EventArgs e)
{
  // Add logic here to populate any data to send

   Response.Clear();
   Response.ClearHeaders();
   Response.AddHeader("Content-Type", "text/plain");  // This can be your data type
   Response.Write("This is plain text");   // This can be your data
   Response.Flush();
   Response.End();

}