0

I have a problem here. I use Ajax call to send data to controller.

define([
    'jquery',
    'Magento_Ui/js/form/components/button'
], function($, button){
    'use strict';

    return button.extend({
        defaults: {
            elementTmpl: 'ui/form/element/button',
            imports: {
                data: '${ $.provider }:data'
            }
        },
        initialize: function () {
            this._super();
            console.log('init');
        },
        sendData: function () {
            console.log('ok');
            let id = this.data.id,
                pattern = $('[name="pattern"]').val(),
                addQty = $('[name="add_qty"]').val(),
                addValue = $('[name="add_value"]').val(),
                expiry = $('[name="expiry"]').val(),
                sendData = {
                    'id': id,
                    'pattern': pattern,
                    'add_qty': addQty,
                    'add_value': addValue,
                    'expiry': expiry,
                },
                generateUrl = this.data.generate_url;

            console.log(sendData);
            console.log(generateUrl);
            console.log(id);
            $.ajax({
                type: 'POST',
                url: generateUrl,
                data: sendData,
                dataType: 'json',
                encode: true,
            });
        }
    })
});

Then my controller do its job.

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
declare(strict_types=1);

namespace Bss\GiftCard\Controller\Adminhtml\GiftCode;

use Bss\GiftCard\Api\GiftCodeRepositoryInterface;
use Bss\GiftCard\Model\GiftCodeFactory;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\RequestInterface;

/**
 * Class Save saves form
 */
class Generate extends Action implements HttpPostActionInterface
{
    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var GiftCodeFactory
     */
    protected $giftCodeFactory;

    /**
     * @var GiftCodeRepositoryInterface
     */
    protected $giftCodeRepositoryInterface;

    /**
     * @param Context $context
     * @param RequestInterface $request
     * @param GiftCodeFactory $giftCodeFactory
     * @param GiftCodeRepositoryInterface $giftCodeRepositoryInterface
     */
    public function __construct(
        Context                             $context,
        RequestInterface                    $request,
        GiftCodeFactory              $giftCodeFactory,
        GiftCodeRepositoryInterface  $giftCodeRepositoryInterface,
    ) {
        parent::__construct($context);
        $this->request = $request;
        $this->giftCodeFactory = $giftCodeFactory;
        $this->giftCodeRepositoryInterface = $giftCodeRepositoryInterface;
    }

    private function generateCode($pattern) {
        do {
            $code = $pattern;
            while (($pos = strpos($code, "{D}"))) {
                $code = substr_replace($code, chr(rand(48, 57)), $pos, 3);
            }
            while (($pos = strpos($code, "{L}"))) {
                $code = substr_replace($code, chr(rand(65, 90)), $pos, 3);
            }
        }
        while ($this->giftCodeRepositoryInterface->checkExisted($code));
        return $code;
    }

    /**
     * Generate code
     *
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\Result\Json|\Magento\Framework\Controller\ResultInterface
     * @throws \Exception
     */
    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();
        try {
            $data = $this->request->getParams();
            if (!isset($data['id'])) {
                $this->messageManager->addErrorMessage("Save Gift Code Pattern first!");
                $resultRedirect->setPath('bss/giftcodepattern/form');
            } else {
                $quantity = (int)$data['add_qty'];
                for ($i = 0; $i < $quantity; $i++) {
                    $resultData = [
                        'pattern_id' => $data['id'],
                        'code' => $this->generateCode($data['pattern']),
                        'status' => \Magento\Config\Model\Config\Source\Enabledisable::ENABLE_VALUE,
                        'current' => $data['add_value'],
                        'initial' => $data['add_value'],
                        'order' => null,
                        'expiry' => $data['expiry'],
                        'sender_name' => null,
                        'sender_email' => null,
                        'recipient_name' => null,
                        'recipient_email' => null,
                        'message' => null,
                    ];
                    $model = $this->giftCodeFactory->create();
                    $model->addData($resultData);
                    $this->giftCodeRepositoryInterface->save($model);
                }
                $this->messageManager->addSuccessMessage(__(
                    'Save Successfully!'
                ));
                $resultRedirect->setPath('bss/giftcodepattern/form', ['id' => $data['id']]);
            }
            return $resultRedirect;
        } catch (\Exception $e) {
            $this->messageManager->addErrorMessage(__(
                'There was an error, please try again!'
            ));
            $resultRedirect->setPath('bss/giftcodepattern/index');
        }
        $resultRedirect->setPath('bss/giftcodepattern/index');
        return $resultRedirect;
    }
}

Then redirect. But I got a problem. My controller generate code and save to database as I expected but NOT redirect. "A technical problem with the server created an error. Try again to continue what you were doing. If the problem persists, try again later." enter image description here enter image description here I could'nt find a solution. I think its caused by ajax call. Could u help me to fix this?

1 Answer 1

0

You cannot redirect page using Ajax.

From W3Schools:

AJAX is a technique for creating fast and dynamic web pages.

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

You need to redirect using : https://stackoverflow.com/a/506004/12004981

2
  • Oh, that mean i cant use $resultRedirect. if i want redirect, i must write it in js file? Jun 7, 2023 at 7:12
  • @NghiaHoangTrong you can use this Ajax code where success and error of your call. you can redirect the page in the success function. Also, you send the return URL from Ajax using json. stackoverflow.com/questions/63205687/…
    – Msquare
    Jun 7, 2023 at 7:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.