12

I have added a simple button in one of my phtml file.

<input type='button' name='emq_zip_btn' class='emq_zip_btn' value='Go'>

I have added one custom js file ("emq.js") from a custom module (Ved_Mymodule) :

require([
    "jquery",
    "jquery/ui"
], function($v){
//<![CDATA[
    $v = jQuery.noConflict();
    $v(document).ready(function() 
    {
        console.log('jquery loaded from emq.js');
        $v(".emq_zip_btn").on('click',function(e)
        {
            console.log('clicked');
        });
    });
//]]>
});

When I click on the above button then "clicked " is printed in the console i.e. jQuery is working properly.

Here is a controller file from a custom module Ved_Mymodule:

Ved\Mymodule\Controller\Index\Index.php:

<?php

namespace Ved\Mymodule\Controller\Index;

use Ved\Mymodule\Model\NewsFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;

class Index extends Action
{
    /**
     * @var \Tutorial\SimpleNews\Model\NewsFactory
     */
    protected $_modelNewsFactory;

    /**
     * @param Context $context
     * @param NewsFactory $modelNewsFactory
     */
    public function __construct(
        Context $context,
        NewsFactory $modelNewsFactory
    ) {
        parent::__construct($context);
        $this->_modelNewsFactory = $modelNewsFactory;
    }

    public function execute()
    {

    }
}

Ved/Mymodule/etc/frontend/routes.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/
App/etc/routes.xsd">
    <router id="standard">
        <route id="news" frontName="news">
            <module name="Ved_Mymodule" />
        </route>
    </router>

My question is how to return a data from this controller method and then access it via jQuery i.e. How to make a simple ajax call after that button clicked.

1
  • vedu can you please explain hoe should I add cuctom checkbox on product detail page.when checked I want to add $0.50 in prodct price which get update in cart to
    – Ashwini
    Commented Jun 23, 2017 at 11:47

1 Answer 1

24

below is the example how to do this, Please modify it according to your requirement.

I used js template for this.

Following example will create drop down in your phtml file using ajax functionality.

In your JS

define([
        'jquery',
        'underscore',
        'mage/template',
        'jquery/list-filter'
        ], function (
            $,
            _,
            template
        ) {
            function main(config, element) {
                var $element = $(element);
var YOUR_URL_HERE = config.AjaxUrl;
                $(document).on('click','yourID_Or_Class',function() {
                        var param = 'ajax=1';
                            $.ajax({
                                showLoader: true,
                                url: YOUR_URL_HERE,
                                data: param,
                                type: "POST",
                                dataType: 'json'
                            }).done(function (data) {
                                $('#test').removeClass('hideme');
                                var html = template('#test', {posts:data}); 
                                $('#test').html(html);
                            });
                    });
            };
        return main;
    });

In Controller

public function __construct(
        Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
    ) {

        $this->resultJsonFactory = $resultJsonFactory;
        parent::__construct($context);
    }


    public function execute()
    {
        $result = $this->resultJsonFactory->create();
        if ($this->getRequest()->isAjax()) 
        {
            $test=Array
            (
                'Firstname' => 'What is your firstname',
                'Email' => 'What is your emailId',
                'Lastname' => 'What is your lastname',
                'Country' => 'Your Country'
            );
            return $result->setData($test);
        }
    }

IN your phtml file

<style>  
.hideme{display:none;}
</style>
<script type="text/x-magento-init">
        {
            "*": {
                "[Namespace]_[Modulename]/js/YOURFILE": {
                    "AjaxUrl": "<?php echo $block->getAjaxUrl(); ?>",
                }
            }
        }
</script>
<div id='test' class="hideme">
    <select>
      <% _.each(posts, function(text,value) { %>
         <option value="<%= value %>"><%= text %></option>
      <% }) %> 
     </select>
</div>

getAjaxUrl should be function in your block file, which return you the url

Hope that helps.

11
  • thank you for your answer. Can you tell me what should I mention in the url parameter of $.ajax method. My controller's frontName is news.
    – vedu
    Commented Aug 3, 2016 at 4:40
  • modulefrontname/index/news thsi will work if your controller path is [namespace]/[modulename]/Controller/Index/News.php I prefer to pass url from template file which creates the url from Block using $this->getUrl
    – Ekta Puri
    Commented Aug 3, 2016 at 4:44
  • yes in magento 1, I also passed url from template file only. but in magento 2 jquery code in template file does not work.
    – vedu
    Commented Aug 3, 2016 at 4:46
  • I updated my answer it has code in phtml file to load you js, but your js should be in your module folder
    – Ekta Puri
    Commented Aug 3, 2016 at 4:49
  • you can access url in js by using config.AjaxUrl
    – Ekta Puri
    Commented Aug 3, 2016 at 4:51

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.