Could you assist me in figuring out how to utilize the POST method in vanilla JavaScript (without jQuery)?
I've been attempting to do so 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);
I keep receiving a 400 error (Bad request). I attempted to execute it in jQuery and it worked, but I specifically need it to work in plain JavaScript.
Any thoughts on why it's not working?
Just for comparison, here is the functional jQuery code:
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);
}
});
}