title: Passing callback functions as arguments in vanilla JS ajax
body: <p>I am working on an ajax function to retrieve info from the database. I set up the API and the ajax function does retrieve proper values, but the callback function I passed as an argument won't work on onreadystatechange.</p>
  
  <p>Simplified Code below</p>
  
  <pre><code>function serializeArgs(args) {
    //Serialize Arguments
  }
  function callback(a) {  //The function to be called as callback
    //Process the response and add contents to the page
  }
  
  function getListData(callback) {
    var ajaxOptions = {
      action: "get_data",
    }
    var request = new XMLHttpRequest();
    request.open("POST", apiurl, true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
    request.setRequestHeader("Accept-language", "en-US");
    request.onreadystatechange = function(event) {
      if (this.readyState == 4 &amp;&amp; this.status == 200) {
        callback(this.response);
      }
    };
    request.send(serializeArgs(ajaxOptions));
  }
  </code></pre>
  
  <p>When I run the function, I get the error "TypeError: callback is not a function"</p>
  
  <p>I have been struggling with this all day, but since I am not that experienced with ajax, I could not figure out why this is happening, and how to solve it. I have a hunch that it has something to do with the asynchronous nature of the ajax, but I'm not sure how I can work around this.</p>