How to clean or flush cache programmatically in magento 2?

Many times we need to clear cache programmatically or using an external script, Using below code snippet we can clear of flush cache programmatically,

<?php
namespace Rbj\Cache\Block;

class CacheClear extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool,
        \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
        array $data = []
    ) {
        $this->_cacheFrontendPool = $cacheFrontendPool;
        $this->_cacheTypeList = $cacheTypeList;
        parent::__construct($context, $data);
    }

     /* Using Product id */
    public function cacheClear()
    {
        /* get all types of cache in system */
        $allTypes = array_keys($this->_cacheTypeList->getTypes());

        /* Clean cached data for specific cache type */
        foreach ($allTypes as $type) {
            $this->_cacheTypeList->cleanType($type);
        }

        /* flushed the Entire cache storage from system, Works like Flush Cache Storage button click on System -> Cache Management */
        foreach ($this->_cacheFrontendPool as $cacheFrontend) {
            $cacheFrontend->getBackend()->clean();
        }
    }
}

Call function like below,
$productStockById = $block->cacheClear();

Get the list of all cache type by just below way,

$allTypes = array_keys($this->_cacheTypeList->getTypes());

Result like below type of all cache,

List of cache types:
array('config','layout','block_html','collections','reflection','db_ddl',
            'eav', 'customer_notification','config_integration','config_integration_api','full_page', 'translate', 'config_webservice');

If you want to flushAll cache, Use below methods,

foreach ($this->_cacheFrontendPool as $cacheFrontend) {
    $cacheFrontend->getBackend()->clean();
}

 

 

How to pass image data using Ajax to server side in backend magento 2?

By default Image data are not post using ajax. only plain data will be passed as Ajax post. if we need to pass image data using ajax we need to call ajax as below way,
Call jquery using requirejs way in backend template file,
Let’s create a simple example of the form,

<form id="abcd" action="" enctype="multipart/form-data">
	<div class="control">
	    <input type='file' class='multi' name='attachment' id='attachment'/>
	</div>
	<button type="button" name="submitajax" id="submitajax"></button> 
</form>
<script>
    require(["jquery"],function($) {
        $("#submitajax").on('click', function() {
            var file = document.getElementById('attachment').files[0];
            var form;
            if (typeof file != 'undefined') {
                form = new FormData(document.getElementById('attachment'));
                form.append('form_key',window.FORM_KEY);
                form.append('attachment', file);
                form.append('id', getId);
            }
            $.ajax({
                url: "<?= $block->getUrl('myajax/custom/urlname'); ?>",
                type: 'post',
                mimeTypes: 'multipart/form-data',
                data: form,
                cache: false,
                contentType: false,  //this is must required
                processData: false, //this is must required
                beforeSend: function() {
                    $('body').trigger('processStart');
                },
                success: function (response) {
                    console.log(response);
                    $('body').trigger('processStop');
                }
            });
        });
    });
</script>

We need to Use You FormData() object of Javascript to store our image data and using above way we can just send image data to server side using ajax.

How to add external CSS and JS Url in Magento2?

You can add External third-party JS,CSS, and fonts URL using Magento 2 by XML at below way, All the Url will be staying in  <head> tag. Pass Second attribute as  src_type=”url”

For set third-party JS link,

<head>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" src_type="url" />
</head>

For set third-party CSS link,

<head>
	<css src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css" src_type="url" />
</head>

For set font link,

<head>
	<link src="http://fonts.googleapis.com/css?family=Montserrat" src_type="url" />
</head>

For Remove link from the page,  If you want to remove specific JS or CSS from the specific page you can use <remove> tag under the <head> to remove from a specific page.

<head>
    <remove src="ttps://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" />
    <remove src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css" />
    <remove src="http://fonts.googleapis.com/css?family=Montserrat" />
</head>