How to redirect to controller using jquery ajax in magento 2.3.5
-
14-04-2021 - |
Question
I want to pass dynamic text-box value to controller using ajax, so if anyone have idea about it then please share with me.
Thanks In Advance
Solution
You can just set below code in your phtml file to use ajax, You have to change your customurl in below code,
<script type="text/javascript">
require(["jquery"],function($) {
$(document).ready(function() {
var customurl = "<?php echo $this->getUrl().'frontname/index/index'?>";
$.ajax({
url: customurl,
type: 'POST',
dataType: 'json',
data: {
customdata1: 'test1',
customdata2: 'test2',
},
complete: function(response) {
dateone = response.responseJSON.default_dateone;
datatwo = response.responseJSON.datatwo;
console.log(datatwo+' '+dateone);
},
error: function (xhr, status, errorThrown) {
console.log('Error happens. Try again.');
}
});
});
});
</script>
inside your controller file execute() method,
<?php
use Magento\Framework\Controller\ResultFactory;
protected $request;
public function __construct(
...
\Magento\Framework\App\Request\Http $request,
...
) {
$this->request = $request;
}
public function execute()
{
$this->request->getParam('your_param'); // get ajax data here
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange