Magento 2.1.0 – How to Make a Simple AJAX Call

ajaxcontrollersmagento2.1.0

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.

Best Answer

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.