jqueryajaxposthttp-status-code-400

Getting 400 bad request error in Jquery Ajax POST


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 ?


Solution

  • 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.