• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
ajax in CI4

#1
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.

[Image: ptf456]

[Image: ptf5l1]

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.
Reply

#2
The problem is solved - at the end of the address of the handler controller in ajax there was a slash. Although, frankly, I did not think that this is such a problem
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.