I have one js file having code as:
function postResponse(url1,param1)
{
var url = intranetUrl + encodeURI(url1);
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function(e)
{
if (this.status == 200)
{
genericRes = this.responseText;
console.log("inside fun:"+genericRes);
return genericRes;
}
alert("!!!"+this.status);
};
xhr.send(param1);
}
Now from another file I want to access this function I had imported above file in this file and call function as:
<script type="text/javascript">
var resss = postResponse("myURL","ACC|^ALL|^M|^|$");
alert("genericRes"+genericRes);
console.log("genericRes>>>"+genericRes);
console.log("resss>>>"+resss);
</script>
But here I got genericRes and resss value as undefined, and above console.log prints first and then it prints console.log("inside fun:"+genericRes); here I got correct output, But from calling code it gives me undefined.
In java we write suppose method which can return String as:
public String myMethod()
{
str = "MyString";
return str;
}
and call that method as:
String str1 = myMethod();
But how to do this in jquery?
Any suggestion will be appreciated. Thanks in advance
If you look carefully, you are defining another function, as in:
So it will return that value to the caller of
xhr.onload, which is the browser and the browser doesn’t do anything with the return value.Furthermore, you cannot really return from asynchronous operations, you have to use a callback.
So:
Then in your code: