The function is working fine. It sends the request to the php file and gets back the right response. I knew this when I use alert function right after assigning xhr.responseText to products variable. However, return function isn’t returning products variable at all. When I alert products after the return function, it gives me nothing.

var api_fetch_input = document.querySelector('.api_fetch_input');
var api_fetch_list = document.querySelector('.api_fetch_input').nextElementSibling;
var index = 0;
var items = 0;
// Fetch Products
function fetch_api_products(query) {
    var products = null;
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            products = xhr.responseText;
    var url = 'products.php?act=search_products&query=' + query;
    url = encodeURI(url);'GET', url , false);
    items = products.length;
    return products;

Please take into consideration that I’m an AB JS learner. Any help please?

Thank you