I want to make a POST to a REST service. When using the standard XMLHttpRequest-way it works, but when using jQuery $.ajax the HTTPRequest headers gets messed up, and the POST becomes OPTIONS.
I'm new to jQuery and HTTP, so I might have missed something obvious :)
This works:
function sendPostXMLHTTP() {
var jData = { "Name": "Olle" };
var client = new XMLHttpRequest();
client.open("POST", "http://localhost:8383/DEMOService/TestPost");
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send(JSON.stringify(jData));
}
This does not work:
function sendPostAjax() {
var jData = { "Name": "Olle" };
$.ajax({
type: 'POST',
url: 'http://localhost:8383/DEMOService/TestPost',
contentType: "text/plain;charset=UTF-8",
data: JSON.stringify(jData)
});
}
HTTPRequest generated from from sendPostXMLHTTP() (correct):
POST http://localhost:8383/DEMOService/TestPost HTTP/1.1
Host: localhost:8383
Connection: keep-alive
Content-Length: 15
Origin: http://localhost:9990
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11
Content-Type: text/plain;charset=UTF-8
Accept: */*
Referer: http://localhost:9990/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
{"Name":"Olle"}
HTTPRequest generated from from sendPostAjax() incorrect:
OPTIONS http://localhost:8383/DEMOService/TestPost HTTP/1.1
Host: localhost:8383
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:9990
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11
Access-Control-Request-Headers: Origin, X-Requested-With, Content-Type, Accept
Accept: */*
Referer: http://localhost:9990/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Why does the "jQuery $.ajax"-way turn the POST into a OPTIONS, and why does the request body disappear?