Welcome Guest, Not a member yet? Register   Sign In
ajax in CI4
#1

(This post was last modified: 11-07-2019, 09:32 PM by dimonisse.)

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

(This post was last modified: 11-13-2019, 12:55 PM by dimonisse.)

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




Theme © iAndrew 2016 - Forum software by © MyBB