0

i had develop magento 2 extension and i have use ajax call to my controller for getting some data. but coding standard provide me some error

Use of echo language construct is discouraged.

my controller code is ......

public function execute()
{  
    echo $mediaUrl.'cs/test/'.$file.$extension;   
}

i had use this code for js

function getFileUrl() {
    jQuery.ajax({
        method: "POST",
        url: "<?php  echo $block->getUrl('modulename/index/index'); ?>",
        data:{itemId:jQuery('input[name=item]').val(),data:jQuery('#file').html() }
    }).done(function(data) {
        jQuery('#file').val(data);
    });
}

if have any solution pleas provide it.

1

2 Answers 2

2

you can try this:

    /** @var \Magento\Framework\Controller\Result\Raw $response */
    $response = $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_RAW);
    $response->setContents('your string here');
    return $response;

or you can try with json

    /** @var \Magento\Framework\Controller\Result\Json $response */
    $response = $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_JSON);
    $response->setData(['success' => true, 'url' => 'your url here']);
    return $response;

But then you have to change your js that handles the ajax response and get the url from response.url.

3
  • how to use response.url in js Commented May 2, 2019 at 6:18
  • in your case data.url
    – Marius
    Commented May 2, 2019 at 6:25
  • ohh i mean that i need to define some thing in require(['jquery', 'jquery/ui','response'] ! 😅😅 Commented May 2, 2019 at 6:28
0

Your execute function expects a return, so you just need to change the echo to return

public function execute()
{  
    $url = $mediaUrl.'cs/test/'.$file.$extension;
    return $url;
}
2
  • return is not working i had try id also but out response is null Commented May 2, 2019 at 6:10
  • try to store in a variable first before passing to return
    – fmsthird
    Commented May 2, 2019 at 6:14

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.