0

i have here a simple code but at the moment i dont find the right way how to code it, can you tell me how i must code it that the function ReadCheck() give me the result from server and not just "undefined"

function Check()
{
            var xhttp = new XMLHttpRequest();
            var data = { nuser: "username", nemail: "email", };
            
            xhttp.open("POST", "api/posts/check", true); 
            xhttp.setRequestHeader("Content-Type", "application/json");
            xhttp.onreadystatechange = function()
            {
            if(this.readyState == 4 && this.status == 200)
             {
                return this.responseText;
             }
            }
            xhttp.send(JSON.stringify(data));
}



function ReadCheck()
{
     console.log(Check());
}
AbsoluteBeginner
  • 1,709
  • 2
  • 8
  • 17
  • `Check` doesn't return anything to be logged inside `ReadCheck`. – DMeneses Apr 24 '21 at 12:48
  • 1
    Please read the [documentation](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send). You probably want to send and also use `onload` to trigger whatever functionality you want when the request has resolved. Your current function does not return anything (because your `if` condition is initially `false`). Which means it returns undefined. You probably want to return a promise resolving when the request has resolved. – tao Apr 24 '21 at 12:49
  • Call Check() and change `return this.responseText;` to whatever you need to do to process the response – mplungjan Apr 24 '21 at 13:00
  • You might find [this](https://jsfiddle.net/websiter/n98tjohy/) useful. – tao Apr 24 '21 at 13:01
  • Also read the answers of [this question](https://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequest). Both methods work (`onreadystatechange` and `onload`). – tao Apr 24 '21 at 13:14
  • You might find this useful. => that was usefull, thanks – James Butler Apr 24 '21 at 14:04

0 Answers0