0

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.

1 Answer 1

0

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']);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.