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
In Controller
IN your phtml file
getAjaxUrl should be function in your block file, which return you the url
Hope that helps.