PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 22, 2022

[FIXED] How I get ajax response from controller in magento 2

 August 22, 2022     ajax, jquery, magento2     No comments   

Issue

I try to make an ajax call and pass the dropdown value in controller and get that particular related order information in view file. Response comes true but how to utilize that response in my view file.

Here is my phtml file:

<select id="chartOption">
   <option value="">Select Option</option>
   <option value="status">Status</option>
   <option value="payments">Payments</option>
   <option value="browser">Browser</option>
</select>
<input type="button" name="chart_button" value="Generate chart" onclick="click_chart()">
<div id="result"></div>
<script type="text/javascript">
        function click_chart() {
            var a = document.getElementById("chartOption");
            var abc = a.options[a.selectedIndex].value;
            data = jQuery(this).serialize();
            jQuery.ajax({
                type: "POST",
                dataType: "json",
                contentType: "application/json",
                url: "Blog/Post/Information", 
                data: "label=" + abc,
                success: function (result) { jQuery('#result').html(result); },
                error: function (error) {  jQuery('#result').html(error); }
            });
        }
</script>

And here is my controller:

public function execute() {
    if (isset($_REQUEST['ajax'])) {
        $label = $this->getRequest()->getPost('label');
        $_orders = $this->getOrders();
        $complete = $pending = $closed = $canceled = $processing = $onHold = 0;
        foreach ($_orders as $_order):
            $label = $_order->getStatusLabel();
            if ($label == 'Complete') {
                $complete++;
            }
            if ($label == 'Pending') {
                $pending++;
            }
            if ($label == 'Closed') {
                $closed++;
            }
            if ($label == 'Canceled') {
                $canceled++;
            }
            if ($label == 'Processing') {
                $processing++;
            }
            if ($label == 'On Hold') {
                $onHold++;
            }
        endforeach;
        $orderData = "['Task', 'Hours per Day'],['Complete'," . $complete . "],['Pending'," . $pending . "]],['Processing'," . $processing . "]],['Canceled'," . $canceled . "]";
        $arr = array('result' => $orderData);
        $jsonData = json_encode(array($arr));
        $this->getResponse()->setHeader('Content-type', 'application/json');
        $this->getResponse()->setBody($jsonData);
    }
}

Solution

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 dropdown in your phtml file. you can use same method to display your data in the format you want.

In your JS

define([
        'jquery',
        'underscore',
        'mage/template',
        'jquery/list-filter'
        ], function (
            $,
            _,
            template
        ) {
            function main(config, element) {
                var $element = $(element);
                $(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>
<div id='test' class="hideme">
    <select>
    <% _.each(posts, function(text,value) { %>
        <option value="<%= value %>"><%= text %></option>
    <% }) %> 
    </select>
</div>

Hope that helps.



Answered By - Ekta Puri
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing