Getting 400 bad request error in Jquery Ajax POST

JqueryAjaxPostHttp Status-Code-400

Jquery Problem Overview


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 ?

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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.

Solution 3 - Jquery

In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.

It turned out to be the anti forgery token.

$.ajax({
        url: "/Cart/AddProduct/",
        data: {
            __RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
            productId: $(this).data("productcode")
        },

The problem was that the .Net controller wasn't set up correctly.

I needed to add the attributes to the controller:

    [AllowAnonymous]
    [IgnoreAntiforgeryToken]
    [DisableCors]
    [HttpPost]
    public async Task<JsonResult> AddProduct(int productId)
    {

The code needs review but for now at least I know what was causing it. 400 error not helpful at all.

Solution 4 - Jquery

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

Solution 5 - Jquery

You need to build query from "data" object using the following function

function buildQuery(obj) {
		var Result= '';
		if(typeof(obj)== 'object') {
			jQuery.each(obj, function(key, value) {
				Result+= (Result) ? '&' : '';
				if(typeof(value)== 'object' && value.length) {
					for(var i=0; i<value.length; i++) {
						Result+= [key+'[]', encodeURIComponent(value[i])].join('=');
					}
				} else {
					Result+= [key, encodeURIComponent(value)].join('=');
				}
			});
		}
		return Result;
	}

and then proceed with

var 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"]
}

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: buildQuery(data),
  error: function(e) {
    console.log(e);
  }
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSachinView Question on Stackoverflow
Solution 1 - JquerySachinView Answer on Stackoverflow
Solution 2 - JqueryDu-LacosteView Answer on Stackoverflow
Solution 3 - JqueryNorbert NorbertsonView Answer on Stackoverflow
Solution 4 - JqueryBenoît SchiexView Answer on Stackoverflow
Solution 5 - JqueryChristian EzeaniView Answer on Stackoverflow