I am trying to get title of a page in sharepoint, to get the title of parent sites i need to make an ajax request
function getPageTitle(variation,option){
var xmlhttp,rootSiteTitle,url;
url=_spPageContextInfo.siteAbsoluteUrl + "/" + variation + "/_api/web?$select=Title";
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
rootSiteTitle=xmlhttp.responseXML.getElementsByTagName("Title")[0].childNodes[0].nodeValue;
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
return rootSiteTitle;
}
Here when i run this request in the console it is setting the value of the variable, but when i use it in code and call the function, the function returns undefined
Is it because the return statement is executed before the request is getting completed? How can i make sure that only after the value is set the function returns the value?