A
A
Alexander2021-01-06 23:40:04
JavaScript
Alexander, 2021-01-06 23:40:04

Why does the request to add Bitrix to the cart via XMLHttpRequest not work?

There is a request

let idElements = 147504;
let countElements = 1;

const request = new XMLHttpRequest();
request.open('POST', '<?=SITE_TEMPLATE_PATH?>/ajax/addtobasket.php');
request.responseType = 'json';
 var data = JSON.stringify({"id": idElements, "count": countElements});

request.addEventListener('readystatechange', () => {
if (request.readyState === 4 && request.status === 200) {
console.log(request.response);
}
});
request.send(data);


There is a conditional request recipient
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");

if (CModule::IncludeModule("sale") && CModule::IncludeModule("catalog")) {

    if (isset($_POST['id']) && isset($_POST['count'])) {
        $PRODUCT_ID = intval($_POST['id']);
        $QUANTITY = intval($_POST['count']);
        Add2BasketByProductID( $PRODUCT_ID, $QUANTITY );
    }
    else { echo "Нет параметров";  }
}
else { echo "Не подключены модули"; }

require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_after.php");


The recipient does not receive anything, the POST request is empty. What could be wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
PetrPo, 2021-01-08
@kikher

BX.ajax({
  url: '<?=\CUtil::jsEscape(SITE_TEMPLATE_PATH)?>/ajax/addtobasket.php',
  method: 'POST',
  data: {"id": idElements, "count": countElements},
  dataType: 'json',
  async: true,
  onsuccess: BX.delegate(function (response) {

  }, this),
  onfailure: BX.delegate(function () {

  }, this)
});

and it’s better to use the Bitrix api, then there will be no such problems
$request = \Bitrix\Main\HttpApplication::getInstance()->getContext()->getRequest();
if($request->isPost() && isset($request['id']) && isset($request['count'])) {

}

L
Lorem Ipsum, 2021-01-06
@GeorgeGeorge

Try this instead of $_POST

$rawData = file_get_contents("php://input");
$jsonData = json_decode($rawData);

And at the front try to fetch

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question