Home > Mobile >  OpenCart 3 - AJAX Query is not working (Invalid token session)
OpenCart 3 - AJAX Query is not working (Invalid token session)

Time:01-30

I try to make POST-request to method of admin controller using AJAX (from admin part). My JS code:

<script>
    $(".remove-request-btn").on('click', function () {
        let request_id = $(this).data('request-id');
        let confirm_result = confirm('Are you sure you want to delete this request?');

        if (confirm_result) {
            $.ajax({
                url: 'index.php?route=extension/x_feedback/settings/removeRequest&token={{ token }}',
                method: 'post',
                dataType: 'json',
                data: {request_id: 11},
                success: function(data) {
                    if (data.status === 'ok') {
                        location.reload();
                    }
                },
                error: function () {
                    alert('Error');
                }
            });
        }
    });
</script>

My method:

public function removeRequest()
{
    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode(
        [
            'status' => 'ok'
        ]
    ));
}

I expect json in the response but get following: enter image description here

I tried to add admin into the url like '/admin/index.php?route=extension/x_feedback/button/feedbackRequest&token={{ token }}' But it doesn't help. Can you help me please what I'm doing wrong? Thank you!

CodePudding user response:

1-please add bellow code into controller method

$data['token'] = $this->session->data['user_token'];

2- use javascript into .twig file - not external js file.

CodePudding user response:

In OC3 is used user_token instead token so you must use this url:

url: 'index.php?route=extension/x_feedback/settings/removeRequest&user_token={{ user_token }}',

And do not forget declare user_token in the corresponding controller file:

$data['user_token'] = $this->session->data['user_token'];
  •  Tags:  
  • Related