I am trying to send an Ajax POST request using Jquery but I am having 400 bad request error.
Here is my code:
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: {
"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);
}
});
It Says: Can not build resource from request. What am I missing ?
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:
May be it will help someone else.
Yes. You need to
stringify
theJSON
data orlse400 bad request
error occurs as it cannot identify the data.Plus you need to add
content type
anddatatype
as well. If not you will encounter415
error which saysUnsupported Media Type
.Try this.
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 :
and pass them in your request
You need to build query from "data" object using the following function
and then proceed with