Magento 2 jquery ajax request

Today topic Magento 2 jquery ajax request. sometime we need to load data with loading the page so for that we need ajax to load data. So today we focus how to use jquery ajax request in magento 2. Magneto have already added the jquery library.you can inject it with require. Here is example of using of jqery ajax for getting the json response from controller.

<script>

require(['jquery', 'jquery/ui'], function($){
    $.ajax({
          method: "POST",
          url: "<?php  echo $block->getUrl('helloworld/ajax/index'); ?>",
          data: { q: "test"},
          dataType: "json"
        })
      .done(function( msg ) {
 
        //do something with you return data
 

      });
   
 });

you we use controller ResultFactory to get back json response.

<?php
namespace QaisarSatti\HelloWorld\Controller\Ajax;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
class Index extends Action {
protected $request;
public function __construct(Context $context,array $data = [])
{
parent::__construct($context,$data);
}
public function execute() {
    $data=array("bdfb");
    $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
    $resultJson->setData($data);
    return $resultJson;

}
}

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

One thought on “Magento 2 jquery ajax request

Leave a Reply