Alexander Kante
Alexander Kante

Reputation: 61

JSON ajax post data - get 400 bad request message

First of all. I read many questions about this problem here in stackoverflow but nothing helps me.

I've this function:

function ip_login(){
    //alert(JSON.stringify(arr_login));
    $.ajax({
        crossdomain: true,
        url: 'https://****/Token',
        type: 'POST',
        data: JSON.stringify(arr_login),   
        contentType: 'application/x-www-form-urlencoded',
        dataType: 'json',
        success: function (data) { 
            console.log(data);
        }
    });        
}

And this is my JSON string:

{"grant_type":"password","username":"[email protected]","password":"blabla"}

With the google chrome extension 'postman' it works fine!

If I test my code above I got the popular 400 bad request message.

When I take the code of the extension 'postman' it doesn't work too.

This is the code of postman:

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://*****/Token",
  "method": "POST",
  "headers": {
    "cache-control": "no-cache",
    "content-type": "application/x-www-form-urlencoded"
  },
  "data": {
    "grant_type": "password",
    "username": "[email protected]",
    "password": "blabla"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

I can't fine my issue..

I searched on Google and SO but no reply helped me.

Edit:

This is in my console:

"NetworkError: 400 Bad Request - https://awesome-url.de/Token"

Upvotes: 3

Views: 3170

Answers (2)

Martinet Lee
Martinet Lee

Reputation: 11

Not sure if this helps, but try anyways. When I'm sending Json, I didn't use "JSON.stringify(arr_login)" All I did was something like "data:{arr_login:arr_login}"

This is how my variable looks like.

var req = new Object();
req["type"] = 'refresh';
req["time"] = window.page_ordertime;

This is how my ajax looks like

$.ajax( {
    url:"listorder_process.php",
    method: "POST",
    dataType:"json",
    data:{request:req}
} )

Upvotes: 0

Manasov Daniel
Manasov Daniel

Reputation: 1378

The problem is in stringifiing JSON. Server expects json but you send string(stringified JSON). Try

function ip_login(){
    //alert(JSON.stringify(arr_login));
    $.ajax({
        crossdomain: true,
        url: 'https://****/Token',
        type: 'POST',
        data: arr_login,   
        contentType: 'application/x-www-form-urlencoded',
        dataType: 'json',
        success: function (data) { 
            console.log(data);
        }
    });        
}

Upvotes: 2

Related Questions