0

I'd like to create unique function for ajax post request.

This is actual source code:

function doAjax(url, postData) {

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        return xhttp.responseText;
    }
  };
  xhttp.open("POST", url, true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send(postData);

}

console.log( doAjax('shipment.php', 'fname=test1&lname=test2') );

But it's not working, the console shows "undefined".

But, if I change return on alert() - everything is OK. So, why return now working ?

Star089
  • 47
  • 2
  • 11

1 Answers1

0

Your function doAjax does not actually return something. When you do xhttp.onreadystatechange = function() {...}; you just set a callback for an event that means this function isn't triggered immediately. No matter what you want to do, you will have to do (or trigger) it inside your callback.