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
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:
According to response variable print your message as follows:
Suppose you want to print message in
<div id="printmessage">
:Run following command:
I hope this may helpful to anyone.
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:
Most likely the problem is related to your JSON return, but I’m not the expert for that 🙂