1

I am trying to make ajax call. But Post call is giving 400 error at "xhr.send( options.hascontent && options.data null )" line.

Below is the code for reference:

$.ajax({
        type: "POST",
        url: "/Security/Login",
        async: false,
        contentType: false,
        beforesend: function (xhr) {
            xhr.setRequestHeader("X-XSRF-TOKEN", $('input:hidden[name =" __RequestVerificationToken"]').val());
        },
        datatype: "json",
        data: "{'Hi'}",        
        processData: false,        
        success: function (response) {

        },
        complete: function (response) {

        }
    });
justDan
  • 2,302
  • 5
  • 20
  • 29
Nayana
  • 11
  • 1
  • 3
  • Why don't you just use the `headers` property to set headers? https://stackoverflow.com/questions/7686827/how-can-i-add-a-custom-http-header-to-ajax-request-with-js-or-jquery – Mitya Sep 05 '19 at 17:57
  • Yes, i tried using headers. It didn't work. Its throwing the same error. – Nayana Sep 05 '19 at 18:00
  • If you have a response code (400) then the issue relates to the receiving web server. Without knowing what it expects, or how it defines that error message, it's hard to know what could be wrong. – Mitya Sep 05 '19 at 18:02

2 Answers2

0
$.ajax({
    type: "POST",
    url: "/Security/Login",
    async: false,
    contentType: false,
    beforesend: function (xhr) {
        xhr.setRequestHeader("X-XSRF-TOKEN", $('input:hidden[name =" __RequestVerificationToken"]').val());
    },
    datatype: "json",
    data: "{'Hi'}",        
    processData: false,        
    success: function (response) {

    },
    complete: function (response) {

    }
});

Bring down the async false after the data part.

KazikM
  • 1,257
  • 5
  • 21
  • 29
0

I got this same error somewhere from my backend code, while I was trying to fill some list on the object I was retrieving from the ajax call. This was while using C# at NET Core.

I was asking for:

// The returned object was:
Event event = new EventViewModel()
{
    IdEvent = null,
    FileStatusList = _operationsService.GetFileStatusList(), // LINE 2
    Comment = null,
};

return Json(event); // to frontend

Getting rid of LINE 2 solved the problem in the frontend for me. And the jQuery ajax call worked as expected.

var data = {
    id: eventId
}

$.ajax({
    url: '../File/Edit', // To Edit method at File controller
    dataType: "json",
    async: true,
    data: data,
    method: "POST",
    success: function (response) {
            // Handle your response here.
    },
    error: function (ex) {
        console.error(ex.responseText);
    },
});
carloswm85
  • 1,396
  • 13
  • 23