Search code examples
javascriptajaxprototypejs

rebuild prototype Ajax POST into "plain" js


What i need is to rebuild prototype.js Ajax request via javascript. (no jQuery / no fetch). IE sopport is required (for some reasons...)

new Ajax.Request(
urlVar,
{
  method: 'post',
  parameters: {elid: document.getElementById('element').selectedIndex},
  onCreate: function(){
    //do somethings
  },
  onComplete: fucnction (event){
    currentValues = eval('(' + event.responseText + ')');
    console.log(currentValues); // will give me an array with 3 objects
  }
});

What i have tried is:

var xhr = new XMLHttpRequest();
xhr.open("POST", urlVar, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function (event) {
   if (xhr.readyState == 4) {
      if (xhr.status == 200) {
         currentValues = eval('(' + event.responseText + ')');
         console.log(currentValues); // i see an error that "currentValues" is undefined
         //i can get 1 object if i will do eval('(' + THIS.responseText + ')');
         // but it still bugs me a lot..

         //other actions here
      }
      else if (xhr.status == 400) {
         console.log('ERROR')
      }
      else {
         console.log('something else other than 200 was returned');
      }
   }
}
xhr.send(document.getElementById('element').selectedIndex);

Maybe someone know which construction will work in this case. Is there some way in order to do onCreate / onComplete via js?


Solution

  • Use this.responseText, xhr.responseText (the same way that you already access .status and .readyState) or event.target.responseText. The event does not have a responseText itself.