Arduino Nano Web Server & Ajax (not quite) working

There's at least one consequential typo in the code you posted, so try this segment instead:

        if (c == '\n' && currentLineIsBlank) {
          client.print(F("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n"));

          if (HTTP_req.startsWith("GET /ajax_switch")) {
            GetSwitchState(client);
          } else {
            client.print(F(R"~~~(<!DOCTYPE html>
<html>
<head>
<title>Arduino Web Page</title>
<script>
function GetSwitchState() {
  var nocache = "nocache=" + Math.random() * 1000000;
  var request = new XMLHttpRequest();
  request.onreadystatechange = function() {
    if (this.readyState == 4) {
      if (this.status == 200) {
        if (this.responseText != null) {
          document.getElementById("switch_txt").innerHTML = this.responseText;
        }}}}
  request.open("GET", "ajax_switch?" + nocache, true);
  request.send(null);
  setTimeout(GetSwitchState, 1000);
}
</script>
</head>
<body onload="GetSwitchState()">
<h1>Arduino AJAX Switch Status</h1>
<div id="switch_txt">Starting...</div>
</body>
</html>
)~~~"));
          }

          Serial.println("<<\n>>");
          Serial.print(HTTP_req);
          HTTP_req = "";
          break;
        }
  • The connection is closed after the response, so don't lie and say Connection: keep-alive -- it is Connection: close
  • Instead of the flaky indexOf check, use the more accurate startsWith along with the request method, GET
    • this would theoretically fix the opposite of what you're seeing
  • Use a raw string for the HTML page content
    • The F() macro can be applied in a single shot
    • Code is less noisy
    • For HTML in particular, no need to escape double-quotes
  • You had </title <script>, which breaks the HTML
  • Added an extra << >> separator when printing the requests to see where they end and begin