I can not get data from AJAX (jQuery Widget)
-
05-01-2021 - |
Question
I need to get data from AJAX, but the Post is empty.
<?php
namespace Namespace\Mymodule\Controller\Query;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
class Custom extends \Magento\Framework\App\Action\Action
{
protected $resultJsonFactory;
public function __construct(
Context $context,
ResultFactory $resultJsonFactory
) {
$this->resultJsonFactory = $resultJsonFactory;
parent::__construct($context);
}
public function execute()
{
var_dump($this->getRequest()->getPost());
$resultJson = $this->resultJsonFactory->create(ResultFactory::TYPE_JSON);
return $resultJson->setData(['success' => test]);
}
}
In the code, Ajax enters, but Ajax does not send anything. Help me please .
define([
'jquery',
'jquery/ui'
], function($) {
"use strict";
$.widget('namespace.module', {
options: {
triggerEvent: 'change',
controller: 'http://developer.loc/namespace_module/query/custom'
},
_create: function() {
console.log('3333');
this._bind();
},
_bind: function() {
var self = this;
self.element.on(self.options.triggerEvent, function() {
console.log('2222');
self._ajaxSubmit();
});
},
_ajaxSubmit: function() {
console.log($('[data-role="cart-item-qty"]').val());
console.log('1111');
console.log(this.options.controller);
$.ajax({
url: this.options.controller,
data: $('[data-role="cart-item-qty"]').val(),
type: 'post',
dataType: 'json',
success: function(res) {
alert('ajax send');
console.log('ajax success');
console.log(res);
}
});
}
});
return $.namespace.module;
});
But if I write in the controller exit (); , then the trigger function success.
Solution
Change your ajax code by following
$.ajax({
url: this.options.controller,
data: 'qty='+$('[data-role="cart-item-qty"]').val(),
type: 'post',
dataType: 'json',
success: function(res) {
alert('ajax send');
console.log('ajax success');
console.log(res);
}
});
Also change your controller execute method by
public function execute()
{
var_dump($this->getRequest()->getPost());
$resultJson = $this->resultJsonFactory->create(ResultFactory::TYPE_JSON);
return $resultJson->setData(['success' => 'test']);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange