I have the Javascript function below. Whenever I run it (calling it from an Android app using WebView), it is sent as an application/x-www-form-urlencoded despite having the dataType: "json" attribute.
If I add contentType: "application/json; charset=utf-8" then the request is not even received from the server and I get error:
XMLHttpRequest cannot load https://example.com/api. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
The request headers look like this:
OPTIONS /api HTTP/1.1
Host: example.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,es;q=0.6
The server is a Java Servlet running on Jetty Embedded that does not even have a WEB-INF or web.xml as it is not a web app but an API. The server does not even receive the request, so I guess it won't be solved by adding response.addHeader("Access-Control-Allow-Origin", "*");
Response header:
HTTP/1.1 200 OK
Allow: POST, TRACE, OPTIONS
Content-Length: 0
Server: Jetty(9.0.z-SNAPSHOT)
Client Javascript
function create(userId, callback) {
  var submitData = {
    "action": "create",
    "userId": userId
  };
  $.ajax({
    data: JSON.stringify(submitData),
    type: "POST",
    url: "https://www.example.com/api",
    dataType: "json"
  })
  .done(function(data) { callback(SUCCESS); })
  .fail(function() { callback(UNKNOWN_ERROR); });
}
EDIT: Tried doing this request without JQuery and still doesn't work.
  var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
  xmlhttp.open("POST", "https://www.example.com/api");
  xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
  xmlhttp.send(JSON.stringify(submitData));
 
    