Search code examples
javascripthtmlpostxmlhttprequestpostman

POST request fails with XMLHttpRequest(), yet works with Postman


I tried sending a POST request to my localhost server. The request works perfectly via Postman, but doesn't seem to work when using XMLHttpRequest(). I debugged the javaScript using Chrome's developer tools, and the JSON body being sent by the XMLHttpRequest() and Postman are identical. I can't figure out why the XMLHttpRequest() is failing, yet Postman's request is succeeding.

I've added the most essential snippets of my JavaScript and HTML code down below. I also made a CSS file to create the UI (not shown).

var signInUrl = 'http://0.0.0.0:8080/user/sign-in';
var signOutUrl = 'http://0.0.0.0:8080/user/sign-out';

function sendEntry(form, signType) {
  var jsonString = serializeEntry(form);
  var httpRequest = new XMLHttpRequest();

  var url = '';
  if (signType === 'signIn') {
    url += signInUrl;
  } else {
    url += signOutUrl;
  }

  httpRequest.open('POST', url, true); // true means asynchronous
  httpRequest.setRequestHeader('Content-type', 'application/json');
  httpRequest.send(jsonString);
}

function serializeEntry(form) {
  var date = new Date();
  var timestamp = date.getTime(); // milliseconds
  var jsonObject = {
    'userId': form.userId.value,
    'time': timestamp
  };
  return JSON.stringify(jsonObject);
}
  <form name="signInOrOut" action="index.html" method="post">
    <div class="signInOrOut">
      <input type="text" name="userId" placeholder="Enter employee ID">
      <br>
      <button id="signInButton" type="submit" name="signInButton" onclick="sendEntry(this.form, 'signIn')">Sign In</button>
      <button id="signOutButton" type="submit" name="signOutButton" onclick="sendEntry(this.form, 'signOut')">Sign Out</button>
    </div>
  </form>

Successful Postman request


Solution

  • You trigger the Ajax request when you submit the form.

    The browser prepares to send the Ajax request. Then the form submits. The browser navigates away from the current page. The JavaScript environment the Ajax request belongs to is destroyed. Then the Ajax request is canceled.

    Either:

    • Cancel the form submission
    • Don't trigger the Ajax request in response to a submit button being clicked