skip to Main Content

Please help me! i’m writing form save stock taking in magento 2, after save -> message not working , if reload page it’s work. Thanks you so much

FUNCTION EXECUTE IN MY CONTROLLER

$data = $this->getRequest()->getParams();
$sku = $data['sku'];
$qty = $data['qty'];
try {
            $objectManager = MagentoFrameworkAppObjectManager::getInstance();
            $productId = $this->product->getIdBySku($sku);
            $product = $objectManager->create('MagentoCatalogModelProduct')->load($productId);
            $stockItem = $this->_stockRegistry->getStockItemBySku($product->getSku());
            $stockItem->setQty($qty);
            $stockItem->save();
            //echo "ok ".$sku;

            $this->messageManager->addSuccessMessage(__('All good'));

        } catch (MagentoFrameworkExceptionNoSuchEntityException $e) {
            //echo "khong co ".$sku;
            $this->messageManager->addErrorMessage(__('This is bad'));
        }
$response = $this->resultFactory
            ->create(MagentoFrameworkControllerResultFactory::TYPE_JSON)
            ->setData([
                'sku' => $sku,
                'qty' => $qty
            ]);
        return $response;

MY JQUERY

require(['jquery','jquery/ui'],function($){
$("#button-unique-identifier-here").click(function(){
    var sku = $("input[name$='general[sku]']").val();
    var stocktaking = $("input[name$='general[stocktaking]']").val();
    url = '/admin/stocktaking/index/save';
    jQuery.ajax({
        url: url,
        dataType: 'json',
        type : 'post',
        data: {sku: sku,qty: stocktaking},
        success: function($response){
                alert("ss");
                console.log($response);
        }
    });
})
});

2

Answers


  1. The addSuccessMessage() and addErrorMessage() functions are working on page reload in Magento. So you need to do some customization to display message after ajax response. Send a JSON response from your controller like follows:

    $data = $this->getRequest()->getParams();
    $sku = $data['sku'];
    $qty = $data['qty'];
    $response = [];
    try {
        $objectManager = MagentoFrameworkAppObjectManager::getInstance();
        $productId = $this->product->getIdBySku($sku);
        $product = $objectManager->create('MagentoCatalogModelProduct')->load($productId);
        $stockItem = $this->_stockRegistry->getStockItemBySku($product->getSku());
        $stockItem->setQty($qty);
        $stockItem->save();
    
        $response = ['error' => false, 'message' => __('All good')];
    }
    catch (MagentoFrameworkExceptionNoSuchEntityException $e) {
        $response = ['error' => true, 'message' => __('This is bad')];
    }
    
    echo json_encode($response); // return response to ajax call in js file
    

    According to response variable print your message as follows:
    Suppose you want to print message in <div id="printmessage">:

    require(['jquery','jquery/ui'],function($){
        $("#button-unique-identifier-here").click(function(){
            var sku = $("input[name$='general[sku]']").val();
            var stocktaking = $("input[name$='general[stocktaking]']").val();
            url = '/admin/stocktaking/index/save';
            jQuery.ajax({
                url: url,
                dataType: 'json',
                type : 'post',
                data: {sku: sku,qty: stocktaking},
                success: function($response) {
                    var res = JSON.parse(JSON.stringify(response));
                    var responseText = JSON.parse(res.responseText);
                    if (responseText.error === true) {
                        $("#printmessage").addClass("error");
                        return false;
                    }
                    else {
                        $("#printmessage").addClass("success");
                    }
                    $("#printmessage").html(responseText.message);
                }
            });
        });
    });
    

    Run following command:

    php bin/magento c:f
    

    I hope this may helpful to anyone.

    Login or Signup to reply.
  2. I don’t see exactly where your problem is, but you can simplify your code a little and load the stockItem directly by the given sku. The following code works for me, if I call it for example directly by URL with parameters sku and qty set:

    $data = $this->getRequest()->getParams();
    $sku = $data['sku'];
    $qty = $data['qty'];
    
    try {
        $objectManager = MagentoFrameworkAppObjectManager::getInstance();
        $stockItem = $this->_stockRegistry->getStockItemBySku($sku);
        $stockItem->setQty($qty);
        $stockItem->save();
        //echo "ok ".$sku;
    
        $this->messageManager->addSuccessMessage(__('All good'));
    
    } catch (MagentoFrameworkExceptionNoSuchEntityException $e) {
        //echo "khong co ".$sku;
        $this->messageManager->addErrorMessage(__('This is bad'));
    }
    $response = $this->resultFactory
                ->create(MagentoFrameworkControllerResultFactory::TYPE_JSON)
                ->setData([
                    'sku' => $sku,
                    'qty' => $qty
                ]);
    return $response;
    

    Most likely the problem is related to your JSON return, but I’m not the expert for that 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search