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 ?
The HyperText Transfer Protocol (HTTP) 400 Bad Request response status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (for example, malformed request syntax, invalid request message framing, or deceptive request routing).
The 400 Bad Request error is an HTTP status code that means that the request you sent to the website server, often something simple like a request to load a web page, was somehow incorrect or corrupted and the server couldn't understand it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With