Vlasta Po
Vlasta Po

Reputation: 901

REST API - POST method in Vanilla JavaScript/AJAX - Error 400 (Bad request)

can you please help me how to get to work POST method in vanilla JS (without jQuery)?

I am trying to do it with this code:

var call =
{
  "filterParameters": {
    "id": 18855843,
    "isInStockOnly": false,
    "newsOnly": false,
    "wearType": 0,
    "orderBy": 0,
    "page": 1,
    "params": {
      "tId": 0,
      "v": []
    },
    "producers": [],
    "sendPrices": true,
    "type": "action",
    "typeId": "",
    "branchId": ""
  }
};
var xhr = new XMLHttpRequest();

xhr.open('POST', 'https://www.alza.cz/Services/RestService.svc/v2/products');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
    if (xhr.status === 200) {
        console.log('OK ' + xhr.responseText);
    }
    else if (xhr.status !== 200) {
        console.log('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send(call);

And constantly getting error 400 (Bad request). I have tried to call it in jQuery and it is working, but I need to get it work in plain JS.

Please, any idea why it is not working?

For check, here is the working code in jQuery:

addData({
  "filterParameters": {
    "id": 18855843,
    "isInStockOnly": false,
    "newsOnly": false,
    "wearType": 0,
    "orderBy": 0,
    "page": 1,
    "params": {
      "tId": 0,
      "v": []
    },
    "producers": [],
    "sendPrices": true,
    "type": "action",
    "typeId": "",
    "branchId": ""
  }
}
);

function addData(data){// pass your data in method
     $.ajax({
             type: "POST",
             url: "https://www.alza.cz/Services/RestService.svc/v2/products",
             data: JSON.stringify(data),// now data come in this function
             contentType: "application/json; charset=utf-8",
             crossDomain: true,
             dataType: "json",
             success: function (data, status, jqXHR) {

                 console.log(data);// write success in " "
             },

             error: function (jqXHR, status) {
                 // error handler
                 console.log(jqXHR);
                 alert('fail' + status.code);
             }
          });
    }

Upvotes: 2

Views: 4142

Answers (3)

Endless
Endless

Reputation: 37915

You must set the content-type header to application/json
You are posting json data as formdata which is wrong
(beside you have forgotten to stringify your object)

xhr.setRequestHeader('Content-Type', 'application/json');

Heres is a working example using the new vanilla js fetch API

var result = null

fetch("https://www.alza.cz/Services/RestService.svc/v2/products", {
  method: "POST",
  body: JSON.stringify({
    "filterParameters": {
      "id": 18855843,
      "isInStockOnly": false,
      "newsOnly": false,
      "wearType": 0,
      "orderBy": 0,
      "page": 1,
      "params": {
        "tId": 0,
        "v": []
      },
      "producers": [],
      "sendPrices": true,
      "type": "action",
      "typeId": "",
      "branchId": ""
    }
  }),
  headers: {"content-type": "application/json"},
  //credentials: 'include'
})
.then(function(res) {
  if (res.ok) { // ok if status is 2xx
    console.log('OK ' + res.statusText);
  } else {
    console.log('Request failed.  Returned status of ' + res.status);
  }

  return res.blob()
})
.then(function(blob) {
  result = blob
  // window.result = blob
})

Upvotes: 4

Tomos Williams
Tomos Williams

Reputation: 2088

So I just tried xhr.send()

and got

XMLHttpRequest cannot load https://www.alza.cz/Services/RestService.svc/v2/products. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://www.alza.cz' that is not equal to the supplied origin.

However if I try this on a blank tab, it actually works. what url are you trying to run this JS from?

Try running the JS from a blank tab.

Upvotes: 0

Calvin
Calvin

Reputation: 149

It's the Access-Control-Allow-Origin response blocking the Javascript code to AJAX access the server data. If the server is not controlled by you, you need another server to fetch the data instead, before it can redirect to your webpage.

Upvotes: 0

Related Questions