3

So, I´ll be needing your help/assistance with these tasks.

I created a search function using Arrows. After testing, I noticed it's not working in IE 11 alone. it works on other browsers though. I later realized that arrow functions won´t work on IE 11. All efforts to make it work have proved abortive.

Please, find below the arrow function and the JS function which I created from the arrow function and its corresponding JS

Arrow function

<script>
    var search = document.getElementById('searchTerm_de');
    var search2 = document.getElementById('searchTerm_en');
    var matchList = document.getElementById('result');

    var searchStates = async searchText => {
        var res = await fetch('../data/info.json');
        var states = await res.json();

        let matches = states.filter(state => {
            var regex = new RegExp(`^${searchText}`,'gi');
            return state.name.match(regex);
        });

        if(searchText.length === 0){
            matches = [];
            matchList.innerHTML = '';
        }
        outputHtml(matches);
    };

    var outputHtml = matches => {
       if(matches.length > 0){
            var html = matches.map(match =>
                `<div class="card result-list de en">
                   <h6><span class="my-result"><a href="${match.url}" target="_blank">${match.name}</a> </h6></span>
               </div>
`).join('');

                matchList.innerHTML = html;
            }
        };
        search.addEventListener('input', () => searchStates(search.value));
        search2.addEventListener('input', () => searchStates(search2.value));
    </script>

Normal JS function (That I created from the arrow function)

<script>

    var search = document.getElementById('searchTerm_de');
    var search2 = document.getElementById('searchTerm_en');
    var matchList = document.getElementById('result');

    var searchStates = async function searchStates (searchText) {
        var res = await fetch('../data/info.json');
        var states = await res.json();
        var matches = states.filter(function (state) {
            var regex = new RegExp("^".concat(searchText), "gi");
            return state.name.match(regex);
        });

        if (searchText.length === 0) {
            matches = [];
            matchList.innerHTML = '';
        };

        outputHtml(matches);
    };

    var outputHtml = function (matches) {
        if (matches.length > 0) {
            var html = matches.map(function (match) {
                return "<div class=\"card result-list de en\">\n\t\t<h6><span class=\"my-result\"><a href=\"".concat(match.url, "\" target=\"_blank\">").concat(match.name, "</a> </h6></span>\n\t</div>\n\t");
            }).join('');
            matchList.innerHTML = html;
        }
    };

    search.addEventListener('input', function () {
        return searchStates(search.value);
    });
    search2.addEventListener('input', function () {
        return searchStates(search2.value);
    });

</script>

JSON File

[
    {
        "name":"Running ",
        "url": "url": "http://google.com"
    },
    {
        "name":"Javascript",
        "url": "url": "http://google.com"
    },
    {
        "name":"On old browser",
        "url": "url": "http://google.com"
    },
    {
        "name":"without arrow",
        "url": "url": "http://google.com"
    },
    {
        "name":"functions and works well",
        "url": "http://google.com"
    },
    {
        "name":"Please, help me",
        "url": "url": "http://google.com"
    },
    {
        "name":"I gladyl appreciate your response",
        "url": "url": "http://google.com"
    },
]

I have change the arrow function and I notice the Await/Async is not supported by IE 11. Is there anyone out there who can make this code work on IE.11 All assistance and help will be clearly appreciated

Thanks

EDIT

I have been able to use the Babel transpiler: https://babeljs.io/docs/en/babel-plugin-transform-async-to-generator/

This is my HTML

              <div class="search">
              <input type="text" class="searchTerm de" id="searchTerm_de" placeholder="Was suchst du ?" onfocus="this.placeholder=''" onblur="this.placeholder='Was suchst du ?'">
              <input type="text" class="searchTerm en" id="searchTerm_en" placeholder="What are you looking for ?" onfocus="this.placeholder=''" onblur="this.placeholder='What are you looking for ?'">
          </div>
              <ul class="list-group-search" id="result"></ul>
              <br/>
          </div> ```

**and this is the transpiled/compiled ES5 for IE 11**


     <script>

            function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error);
          return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

      function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args
      ); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

      var search = document.getElementById('searchTerm_de');
      var search2 = document.getElementById('searchTerm_en');
      var matchList = document.getElementById('result');

      var searchStates =  function () {
              var _ref = _asyncToGenerator(function* (searchText) {
                  var res = yield fetch('./data/info.json');
                  var states = yield res.json();
                  let matches = states.filter(function(state) {
                      var regex = new RegExp(`^${searchText}`, 'gi');
                      return state.name.match(regex);
                  });

                  if (searchText.length === 0) {
                      matches = [];
                      matchList.innerHTML = '';
                  }

                  outputHtml(matches);
              });

              return function searchStates(_x) {
                  return _ref.apply(this, arguments);
              };
          }();

      var outputHtml =function(matches) {
          if (matches.length > 0) {
              var html = matches.map(match => `<div class="card result-list de en">
              <h6><span class="my-result"><a href="${match.url}" target="_blank">${match.name}</a> </h6></span>
      </div>
      `).join('');
              matchList.innerHTML = html;
          }
      };

      search.addEventListener('input', () => searchStates(search.value));
      search2.addEventListener('input', () => searchStates(search2.value));

      </script>

While the JSON file still remains the same.

It's still working on all browsers except IE 11.

Its gettings tiring but I'm not determined to give up

Anyone else knows what could be done at this point to make the code run on IE 11

Thanks
Olasunkanmi
  • 902
  • 15
  • 23
  • 1
    `await`, `async`, template literals and arrow functions are not supported in ES5. Arrow functions are very similar to `function(){}`. Template literals can be replaced by something like: `"..." + variable1 + "..." + variable2`. `async` and `await` need to be replaced with `Promises` (or polyfill) – nick zoum Nov 19 '19 at 12:30
  • you need [babel](https://babeljs.io/) – Vishnu Bhadoriya Nov 19 '19 at 12:31
  • @VishnuBhadoriya I used babel as well, and still the error persists. Can you help me look into this code please ? Thanks – Olasunkanmi Nov 19 '19 at 12:56
  • 1
    @nickzoum Thanks for the quick response. So, what would you advice that I change in the code Thanks – Olasunkanmi Nov 19 '19 at 12:58
  • @AdenijiOlasunkanmi if your error is related to async,awit in babel then refer this [link](https://medium.com/@binyamin/enabling-async-await-and-generator-functions-in-babel-node-and-express-71e941b183e2) – Vishnu Bhadoriya Nov 19 '19 at 13:13
  • @VishnuBhadoriya Thanks for the response once more. I could barely understand the writeup. Do I have to install Babel in my project or I can simply use the website. A step by step approach will be appreciated – Olasunkanmi Nov 19 '19 at 13:21
  • you need to _install_ babel – HolyMoly Nov 24 '19 at 23:51
  • @HolyMoly I have installed babel transpiler and still not working – Olasunkanmi Nov 24 '19 at 23:52
  • you may have to do some configuring, it get's tricky. you should post whatever errors you are getting and add it to your question, but installing babel is the right first step. with an updated question you may get help in getting past the babel setup – HolyMoly Nov 24 '19 at 23:54
  • Hello @HolyMoly, Thanks once more for the response. I have installed babel on my development environment and used the transpiler plugin. But yet, no result. I´ll re-write the steps I have taken so far and update my question. Thanks for the tips – Olasunkanmi Nov 25 '19 at 00:07

4 Answers4

3

Check this link

I used babel repl to generate IE compatible code. You should follow the instructions @David Barshav mentioned but you need to configure your babel correctly to work with IE 11. Also you should check preset-env for babel.

Edit : Well the code transpiled below is just a workable version of javascript. But the missing part is fetch is not supported by IE 11. You have to use a polyfill for that or use XHR request or use a library that simplifies making XHR requests (like jquery).

Github Fetch poyfill. BluebirdPromise polyfill.

The generated code :

var search = document.getElementById('searchTerm_de');
var search2 = document.getElementById('searchTerm_en');
var matchList = document.getElementById('result');

var searchStates = function searchStates(searchText) {
  var res, states, matches;
  return regeneratorRuntime.async(function searchStates$(_context) {
    while (1) {
      switch (_context.prev = _context.next) {
        case 0:
          _context.next = 2;
          return regeneratorRuntime.awrap(fetch('../data/info.json'));

        case 2:
          res = _context.sent;
          _context.next = 5;
          return regeneratorRuntime.awrap(res.json());

        case 5:
          states = _context.sent;
          matches = states.filter(function (state) {
            var regex = new RegExp("^".concat(searchText), "gi");
            return state.name.match(regex);
          });

          if (searchText.length === 0) {
            matches = [];
            matchList.innerHTML = '';
          }

          ;
          outputHtml(matches);

        case 10:
        case "end":
          return _context.stop();
      }
    }
  });
};

var outputHtml = function outputHtml(matches) {
  if (matches.length > 0) {
    var html = matches.map(function (match) {
      return "<div class=\"card result-list de en\">\n\t\t<h6><span class=\"my-result\"><a href=\"".concat(match.url, "\" target=\"_blank\">").concat(match.name, "</a> </h6></span>\n\t</div>\n\t");
    }).join('');
    matchList.innerHTML = html;
  }
};

search.addEventListener('input', function () {
  return searchStates(search.value);
});
search2.addEventListener('input', function () {
  return searchStates(search2.value);
});
Eldar
  • 9,781
  • 2
  • 10
  • 35
  • I was going to suggest using either the TypeScript/bable compiler (you beat me to it) – dbones Dec 01 '19 at 23:23
  • Hi @dbones I still have issues with it.. can you expanciate further? – Olasunkanmi Dec 02 '19 at 14:03
  • @AdenijiOlasunkanmi can you explain issues you are having? Giving the detailed errors etc. – Eldar Dec 02 '19 at 14:12
  • Hi @Eldar Thanks for your willingness to help a newbie developer. I have been using the code on this platform and it's not fetching the data from the JSON file. Can you check the link here: https://jsbin.com/fiwoqaveje/edit?html,js,output – Olasunkanmi Dec 03 '19 at 10:27
  • @AdenijiOlasunkanmi your requests actually are blocked. Because you are making http requests from https. and also your api provide should allow CORS and you should also add your your request cors headers. – Eldar Dec 03 '19 at 10:40
  • @Eldar Thanks once more. I actually used the JSON on a URL because I wanted you to see the JSON file and also test run it. I actually use this code on my local computer and it works. Do you have an alternative where the codes can be posted or maybe we can do some remote view thingy.. Thanks so much for the suppoort – Olasunkanmi Dec 03 '19 at 11:22
  • @AdenijiOlasunkanmi no matter where you post it it will be CORS request and it wont work unless you configure backend to allow it. – Eldar Dec 03 '19 at 11:25
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/203523/discussion-between-adeniji-olasunkanmi-and-eldar). – Olasunkanmi Dec 03 '19 at 11:45
  • @AdenijiOlasunkanmi I also came up with the same answer as Elder mention above! problem is the promise which is rejected when we request! – Ericgit Dec 03 '19 at 19:02
2

To enable support for async in IE 11 you need to make sure you are including the Regenerator Runtime in your page. This can either be loaded directly, or included via babel-transform-runtime.

David Bradshaw
  • 11,859
  • 3
  • 41
  • 70
  • Hi @David, thanks for the response. I have re-generated the code using the babel transpiler/compiler, but its still the same. no changes ! – Olasunkanmi Dec 02 '19 at 14:07
  • I guess their is something else missing in your Babel Config then. You code above looks fine and should work if Babel is set correctly. – David Bradshaw Dec 02 '19 at 15:41
1

the easiest way is to use bable and specify to use a presets for IE11

.bablerc

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 2 versions", "ie >= 11"]
      },
        "useBuiltIns": true
    }],

  ]
}

and use CLI with flag --presets babel-preset-es2015-ie

Using bable online tester

Bable Tester

Barkermn01
  • 6,781
  • 33
  • 83
  • Hi @Martin Thanks for your willingness to help a newbie developer. I have been using the code on this platform and it's not fetching the data from the JSON file. Can you check the link here: https://jsbin.com/fiwoqaveje/edit?html,js,output – Olasunkanmi Dec 03 '19 at 10:28
  • Hello again, Please, find the Non-transpiled code here: https://jsbin.com/lovimapaca/1/edit?html,js,output – Olasunkanmi Dec 03 '19 at 12:50
  • The above code works will in Chrome, Mozilla and Internet Edge but does not work on IE.11 – Olasunkanmi Dec 03 '19 at 12:54
  • Added a link to the setup in bable try it online for you, that seems to be IE 11 compatible. – Barkermn01 Dec 03 '19 at 18:38
0

I just converted to old version using babel preset,run-time and re-generator and It'll work in IE.

var search = document.getElementById('searchTerm_de');
var search2 = document.getElementById('searchTerm_en');
var matchList = document.getElementById('result');

var searchStates = function searchStates(searchText) {
  var res, states, matches;
  return _regenerator.default.async(function searchStates$(_context2) {
    while (1) {
      switch (_context2.prev = _context2.next) {
        case 0:
          _context2.next = 2;
          return _regenerator.default.awrap(fetch('../data/info.json'));

        case 2:
          res = _context2.sent;
          _context2.next = 5;
          return _regenerator.default.awrap(res.json());

        case 5:
          states = _context2.sent;
          matches = states.filter(function (state) {
            var regex = new RegExp("^".concat(searchText), 'gi');
            return state.name.match(regex);
          });

          if (searchText.length === 0) {
            matches = [];
            matchList.innerHTML = '';
          }

          outputHtml(matches);

        case 9:
        case "end":
          return _context2.stop();
      }
    }
  });
};

var outputHtml = function outputHtml(matches) {
  if (matches.length > 0) {
    var html = matches.map(function (match) {
      return "<div class=\"card result-list de en\">\n               <h6><span class=\"my-result\"><a href=\"".concat(match.url, "\" target=\"_blank\">").concat(match.name, "</a> </h6></span>\n           </div>\n");
    }).join('');
    matchList.innerHTML = html;
  }
};

search.addEventListener('input', function () {
  return searchStates(search.value);
});
search2.addEventListener('input', function () {
  return searchStates(search2.value);
});

I'm using presets for this code to transform from asyn to IE! If it's not working, let us know, so we can assist you better!

Happy codin'!

Ericgit
  • 6,089
  • 2
  • 42
  • 53
  • Hello @bloodyLogic, Thanks for the kind assistance. I have also tried this method using babel/plugin-transform-async-to-generator. It generated the same result for me, and still not working. Can you confirm from your side ? Thanks – Olasunkanmi Nov 25 '19 at 13:27
  • Thanks once more.. my company still uses IE 11. don´t know why, but it has remained so. Hence,I need to make this work on IE 11. what else would you suggest? – Olasunkanmi Nov 25 '19 at 13:41
  • try babel with script like ec15,17, and try to console where is bug, to figure out try to solve your own or share here with us! – Ericgit Nov 25 '19 at 13:43
  • Sure,I´m trying to do that.. will share the result here once I´m done with my findings Thanks once more for your support – Olasunkanmi Nov 25 '19 at 13:48
  • 1
    This code can't work on IE. It has generator functions, arrow functions . `function* (searchText)` and `() => searchStates(search.value)` is not supported in IE. – Eldar Nov 30 '19 at 12:05
  • @Eldar, what do you think can be done for this to work ? – Olasunkanmi Dec 02 '19 at 14:05
  • @AdenijiOlasunkanmi I just update the code, please check it and I hope it'd work because I use `@babel/preset-env`. in the last code there was alot of new version code, so that why it's not working! you should Learn webpack to solve this kinda problems, I think! – Ericgit Dec 02 '19 at 16:36
  • @AdenijiOlasunkanmi it's working here https://www.browserling.com/browse/win/7/ie/11/https%3A%2F%2Fjsbin.com%2Fleneluj%2Fedit%3Fhtml%2Cjs%2Coutput – Ericgit Dec 02 '19 at 17:08
  • @BloodyLogic Thanks again for the insightful help. I checked the link, used the code and its still same. You didn´t test it with the JSON file to know if its actually picking those data from the JSON file – Olasunkanmi Dec 03 '19 at 10:13
  • See what I´m trying to do here: https://jsbin.com/fiwoqaveje/edit?html,js,output – Olasunkanmi Dec 03 '19 at 10:29
  • @BloodyLogic I have noticed that fetch, res, RegExp, are not supported in IE 11.. what do you think can be done to remedy this? Thanks – Olasunkanmi Dec 04 '19 at 15:29
  • @Olasunkanmi I just found this for you, he is using polyfill https://stackoverflow.com/questions/37258632/react-fetch-not-working-in-ie11 – Ericgit Dec 06 '19 at 04:48