Hi to all.
I started to deal with CI 4, until that time I had been working with version 3 for several years. There was a problem - I can not transfer data to the controller using Ajax. I suspect that the case is in csrf_token, but did not find a clear explanation in the documentation. In general, here is a view code
Code:
<input type="hidden" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>" id="csrf"/>
<button type="button" class="incart" onclick="inCart(<?= $product[0]['product_id'] ?>)"><?= lang('Language.incart'); ?></button>
Code:
function inCart(prod_id) {
$.ajax({
url: '/product/inCart/',
type: 'post',
dataType:'json',
data: {id: prod_id,csrf_token: $('#csrf').val()},
success: function (html) {
alert('Product in cart'+prod_id);
},
})
}
at this stage everything seems to be fine, trying to get my data in the controller
PHP Code:
if ($this->request->isAJAX()) {
$prodID = service('request')->getPost('id');
var_dump($this->request->getPost('id'));
}
and the output is null
in the console I saw just such a picture - at first the data arrives, but then they redirect themselves to themselves and without data.
Something is clearly wrong here.
after thinking and searching in google, I found a solution that doesn’t quite suit me, but it works - instead of using the POST method I use GET, and then despite the redirects from 301 to 200, the data comes to the controller.