Error while calling an API through ajax
-
16-02-2021 - |
Question
I have added a code inside the script tag for an on-change function.
But i am m getting error like this
Server cannot understand Content-Type HTTP header media type application/x-www-form-urlencoded
And the code added in phtml file is as follows:
<script type="text/javascript">
require(["jquery"],function($) {
$(document).ready(function () {
$('#sellerList').change(function () {
$.ajax({
url: "/rest/default/V1/Ivy/ChangeCustomPrice",
data: {
"changeRequest": {
"product_id": $('#sellerList').value,
"seller_id": <?php echo $_product->getId(); ?>
}
},
type: 'POST',
dataType: 'application/json',
showLoader: true,
success: function(data, status, xhr) {
console.log("success");
},
error: function (xhr, status, errorThrown) {
console.log('Error happens. Try again.');
console.log(errorThrown);
}
});
})
});
});
</script>
Can anyone say what am i doing wrong here?
Solution
This worked for me
I replaced the code as below
<script type="text/javascript">
require(["jquery"],function($) {
$(document).ready(function () {
$('#sellerList').change(function () {
var changedSeller = $('#sellerList').val();
var requestData = JSON.stringify({
changeRequest: {
seller_id: changedSeller,
product_id: <?php echo $_product->getId(); ?>
}
});
$.ajax({
url: "/staging/restaurantwarecom/rest/default/V1/Ivy/ChangeCustomPrice",
data: requestData,
type: 'POST',
contentType: "application/json",
dataType: "json",
showLoader: true,
success: function(data, status, xhr) {
console.log("Success");
},
error: function (xhr, status, errorThrown) {
console.log('Error happens. Try again.');
console.log(errorThrown);
}
});
})
});
});
This might be helpful for someone.
Thanks
OTHER TIPS
Magento do not support urlencoded requests.
Please specify content type: Add "Content-type: application/json" to curl command and send in body parameter as {"product_id": 12, "seller_id":22}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange