title: Javascript Ajax frontend call to asp.net C# backend
body: <p>I am trying to accomplish simple yet seems complicated task. I am trying to make AJAX call from pure JavaScript (front end) to aspx page (back end) without including any asp ajax library aiming no asp page rendering on front end i.e. only html+JS for front end.</p>
  
  <p>So here is how it goes, on the front end this js code will send asynchronous call to asp page with a variable. The variable is derived from text box value. </p>
  
  <pre><code> function handleRequest() {
      if (xhr.readyState &lt; 4) {
          return; // The response is not available yet , we do nothing
      }
      if (xhr.status !== 200) {
          alert('Error!'); // error HTTP
          return;
      }
  }
  function getValue() {
      var textVal = document.getElementById("test1").value;
      xhr.open('GET', 'WebForm1.aspx?q=' + textVal , true);
      xhr.send();
      var response = xhr.responseText;
      document.getElementById("bdy").innerHTML = response;
  }
  
  var btn = document.querySelector("button");
  var xhr = new XMLHttpRequest();
  var body = document.getElementById("bdy");
  xhr.onreadystatechange = handleRequest;
  document.getElementById("header").innerHTML = Date();
  btn.addEventListener('click', getValue, true);
  </code></pre>
  
  <p>Now, on the back end asp code which will echo the textbox value with the time stamp from the server.</p>
  
  <pre><code>protected void Page_Load(object sender, EventArgs e)
          {
              string getRequest = Request.QueryString["q"];
              DateTime dt = DateTime.Now;
              string responseText = getRequest + dt.ToString();
              Response.Write(responseText);
          }
  </code></pre>
  
  <p>Finally, this code works perfect when I make synchronous call i.e.
  xhr.open('GET', 'WebForm1.aspx?q=' + temp, false); but fails if I send asynchronous call i.e. xhr.open('GET', 'WebForm1.aspx?q=' + temp, true);</p>
  
  <p>I would really appreciate your help.</p>