I'm trying to send some data to my Controller from a template.html using Ajax, so my checkout page does not refresh when I send a custom form, but I don't get anything, the information is an extra field for the sales order, and the fields are empty.
This is my code from the template. This code is just after the </form>
<script type="text/javascript">
require([
"jquery",
"mage/mage"
],function($) {
$(document).ready(function() {
$('#co-shipping-form').mage(
'validation',
{
submitHandler: function(form) {
$.ajax({
url: "http://(my server IP)/(folder name)/checkout/Ordercomment/index",
data: {comments: 'Test comment from Ajax '},
type: 'POST',
dataType: 'json',
beforeSend: function() {
// show some loading icon
},
success: function(data, status, xhr) {
// data contains your controller response
},
error: function (xhr, status, errorThrown) {
console.log('Error happens. Try again.');
console.log(errorThrown);
}
});
}
}
);
});
});
</script>
Then this is the part of the controller where I'm trying to receive the data.
namespace Vsourz\Ordercomment\Controller\Ordercomment;
use Magento\Framework\Controller\ResultFactory;
class Index extends \Vsourz\Ordercomment\Controller\Index
{
public function execute()
{
$response = $this->resultFactory
->create(\Magento\Framework\Controller\ResultFactory::TYPE_JSON)
->setData([
'status' => "ok",
'message' => "form submitted correctly"
]);
return $response;
//This is the field where I want to store the data that comes from Ajax
$Ordercomments = $this->getRequest()->getPost('comments');
I hope someone can help me! Thank you!