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." I could'nt find a solution. I think its caused by ajax call. Could u help me to fix this?