FACG5 / asi-autocomplete

http://asi-auto.herokuapp.com/
0 stars 0 forks source link

XHR Abstraction #27

Closed MohammedYehia closed 6 years ago

MohammedYehia commented 6 years ago

https://github.com/FACG5/asi-autocomplete/blob/0f66d3d22af5ace2719bc050d614ef64b13e0c47/public/js/logic.js#L3-L30

those two functions are the same but with different parameters so try to build one function that receives a method, URL, and other things if you want as parameters.

HemaSAli commented 6 years ago

@MohammedYehia Thanks Mohammed , I did it

function xhrRequest(url, method, data, cb) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        if (method === "GET") {
          var result = JSON.parse(xhr.responseText);
          cb(result);
        } else if (method === "POST") {
          cb();
        }
      }
    }
  };

  xhr.open(method, url, true);
  xhr.send(JSON.stringify(data));
}