Reputation: 1
I have the following HTML. It is supposed to do a POST to a server (in the MWE below, I just did it with cnn.com).
However, it doesn't do what I expect, which is formatting the POST request in a JSON format. Instead, it gives the following
x1=y1&x2=y2
as the Request Body
while it should give something like
{ "x1": "y1", "x2": "y2"}
for the server to respond properly.
Here is the code:
<!-- jQuery Version 1.11.0 -->
<script src="js/jquery-1.11.0.js" }}"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js" }}"></script>
<!-- Plugin JavaScript -->
<script src="js/jquery.easing.min.js" }}"></script>
<script src="js/classie.js" }}"></script>
<script src="js/cbpAnimatedHeader.js" }}"></script>
<!-- Contact Form JavaScript -->
<script src="js/jqBootstrapValidation.js" }}"></script>
<!--
<script src="js/contact_me.js" }}"></script>
-->
<!-- Custom Theme JavaScript -->
<script src="js/freelancer.js" }}"></script>
<form action="" method="post" name="demoform" id="demoform">
<input type=hidden name=x1 value=y1 id=x1>
<input type=hidden name=x2 value=y2 id=x2>
<input type="button" value="demo" name="button" id="button">
</form>
<script>
$.sendRequest = function(form) {
$.ajax({
type: "POST",
url: "http://www.cnn.com",
data: form.serialize(),
dataType: 'application/json',
success: function(data, textStatus){
}
});
}
$('#button').click(function () {
$.sendRequest($("#demoform"));
});
</script>
Just as a note, I want to do the equivalent of:
curl -X POST "https://www.cnn.com" -H "accept: application/json" -H "Content-Type: application/json" -d "{ \"x1\": \"y1\", \"x2\": \"y2\"}"
EDIT: I will note that when I do "Inspect" in the browser, and check the request headers, they are not what expected, they have many additional things, and none of the things such as content-type: application/json that I added following the comment below. (instead it shows content-type: text/html). I am not sure why it completely ignores my headers.
Upvotes: 0
Views: 51
Reputation: 943585
dataType: 'application/json',
dataType describes the format you expect to receive back from the server and doesn't take a MIME type.
contentType describes the format you are sending.
Change that to:
dataType: "json",
contentType: "application/json",
data: form.serialize(),
This function URL encodes the data in a form. You need to construct an object and convert it to JSON.
data: JSON.stringify({ foo: "some value", bar: "some value" }),
Upvotes: 2