Getting 400 bad request error in Jquery Ajax POST Getting 400 bad request error in Jquery Ajax POST ajax ajax

Getting 400 bad request error in Jquery Ajax POST


Finally, I got the mistake and the reason was I need to stringify the JSON data I was sending. I have to set the content type and datatype in XHR object.So the correct version is here:

$.ajax({  type: 'POST',  url: "http://localhost:8080/project/server/rest/subjects",  data: JSON.stringify({    "subject:title":"Test Name",    "subject:description":"Creating test subject to check POST method API",    "sub:tags": ["facebook:work", "facebook:likes"],    "sampleSize" : 10,    "values": ["science", "machine-learning"]  }),  error: function(e) {    console.log(e);  },  dataType: "json",  contentType: "application/json"});

May be it will help someone else.


Yes. You need to stringify the JSON data orlse 400 bad request error occurs as it cannot identify the data.

400 Bad Request

Bad Request. Your browser sent a request that this server could not understand.

Plus you need to add content type and datatype as well. If not you will encounter 415 error which says Unsupported Media Type.

415 Unsupported Media Type

Try this.

var newData =   {                  "subject:title":"Test Name",                  "subject:description":"Creating test subject to check POST method API",                  "sub:tags": ["facebook:work", "facebook:likes"],                  "sampleSize" : 10,                  "values": ["science", "machine-learning"]                  };var dataJson = JSON.stringify(newData);$.ajax({  type: 'POST',  url: "http://localhost:8080/project/server/rest/subjects",  data: dataJson,  error: function(e) {    console.log(e);  },  dataType: "json",  contentType: "application/json"});

With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.


The question is a bit old... but just in case somebody faces the error 400, it may also come from the need to post csrfToken as a parameter to the post request.

You have to get name and value from craft in your template :

<script type="text/javascript">    window.csrfTokenName = "{{ craft.config.csrfTokenName|e('js') }}";    window.csrfTokenValue = "{{ craft.request.csrfToken|e('js') }}";</script>

and pass them in your request

data: window.csrfTokenName+"="+window.csrfTokenValue