1

Following code is not working and not returning proper result.

function test(file) {
 var uri = "http://localhost/test.php";
 var xhr = new XMLHttpRequest();
 var result="done";
 xhr.open("POST", uri, true);
 xhr.send();
 xhr.onloadend=function()
  {
   result=xhr.responseText;
   return result;
  }
} 

Is it wrong to return from event handlers or it just returns result back to test function?

1

2 Answers 2

1

returning in an event handler, as you are doing, will not return results back to the calling scope. The DOM event function you are using to attach the listener to disregards the return value. If you are trying to access the result from onload you will need to do so in a callback

function test(file, callback){
    var uri = "http://localhost/test.php";  
    var xhr = new XMLHttpRequest();  
    xhr.open("POST", uri, true);  
    xhr.send(formdata);
    xhr.onload=function(){
        callback(xhr.responseText);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

It is okay to return from event handlers, but your return value doesn't go where you apparently think it goes. In most cases, event handlers are expected to only return true or false, which indicates whether you want to disable the default behavior or not (false means "suppress the default behavior for this event"). It is not possible to receive the return value of your onloadend handler in either your test() function or as a return value of your test() function, because the event handler is executed asynchronously, at a time when your function has already returned.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.