0

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?

Vignesh Subramanian
  • 7,161
  • 14
  • 87
  • 150
  • 1
    *"Is it because the return statement is executed before the request is getting completed?"* yes – Felix Kling Jun 10 '15 at 18:28
  • the solutions provided are for jquery and not for javascript. is there a way i can use promises or deferred calls in javascript? – Vignesh Subramanian Jun 10 '15 at 18:32
  • If you read the answer carefully you will notice that jQuery is just an example, and that the solutions are not jQuery specific (except the one about deferred objects). Promises and callbacks have nothing to do with jQuery. You can also look at the second answer though, which doesn't refer to jQuery at all. – Felix Kling Jun 10 '15 at 18:34

0 Answers0