8

im new in javascript and php , my goal is :RETURN string from xmlhttp responseText to a function return value.So i can use it with innerText or innerHTML method. the html code :

<script>
function loadXMLDoc(myurl){
    var xmlhttp;
    if (window.XMLHttpRequest){
        xmlhttp=new XMLHttpRequest();}
    else{
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}

     xmlhttp.onreadystatechange=function(){
         if (xmlhttp.readyState==4 && xmlhttp.status==200){
              xmlhttp.responseText;}
     }

    xmlhttp.open("GET",myurl,true);
    xmlhttp.send();
}
</script>
inogbox
  • 103
  • 1
  • 1
  • 6
  • 1
    Don't use `innerText`: it's a Microsoft proprietary member, and although is supported by Chrome it isn't by Firefox for example. Use it as a fallback if `textContent` isn't supported (IE8 and older). – MaxArt Sep 14 '12 at 09:50

2 Answers2

11

You can't.

Neither runs the code syncronous, nor would you return anything to loadXMLDoc but to the anonymous function which is the onreadystatechange handler.

Your best shot is to pass a callback function.

function loadXMLDoc(myurl, cb) 
{
   // Fallback to Microsoft.XMLHTTP if XMLHttpRequest does not exist.
   var xhr = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));

    xhr.onreadystatechange = function()
    {
        if (xhr.readyState == 4 && xhr.status == 200)
        {
            if (typeof cb === 'function') cb(xhr.responseText);
        }
    }

   xhr.open("GET", myurl, true);
   xhr.send();

}

And then call it like

loadXMLDoc('/foobar.php', function(responseText) {
    // do something with the responseText here
});
jAndy
  • 231,737
  • 57
  • 305
  • 359
  • to jAndy: iwant loadXMLdoc function it self as returing value so i can make simple function to set innerText or innerHTML in element, can this possible? – inogbox Sep 14 '12 at 10:00
  • @inogbox: not as long as your ajax request runs in asynronous mode (which is highly recommendable). You can manually set the request to *sync*, which would mean that it will lock down and freeze the browser-UI everytime the request is running. You could do that by setting the third paremeter of `.open()` to `false`. – jAndy Sep 14 '12 at 10:14
  • my goal is using asynronous mode, so i must create handler to pass the response text? – inogbox Sep 14 '12 at 10:31
  • why your code cannot run? even im using alert() function when i call it does't return anything – inogbox Sep 14 '12 at 10:35
  • @inogbox: my code won't run ? Anyway - there is **no way** to return anything in that constelation and an asyncronous request. You have to either choose between a synced request or using the callback-method like I demonstrated. – jAndy Sep 14 '12 at 12:59
  • yes i copy and paste your code in my code editor and also i create function to execute loadXMLDoc, and i put alert() function in '//do something with the responseText here', nothing happen, the message box i expected not showing can you tell me whats wrong? – inogbox Sep 14 '12 at 15:34
4

Just return the responseText property or assign its value to a variable in closure.

Returning a value:

<script>
    function loadXMLDoc(myurl) {
        var xmlhttp;
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        } else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                return xmlhttp.responseText;
            }
        }

        xmlhttp.open("GET", myurl, true);
        xmlhttp.send();
        return xmlhttp.onreadystatechange();
    }
</script>

Using a closure:

<script>
    var myValue = "",
        loadXMLDoc = function (myurl) {
            var xmlhttp;
            if (window.XMLHttpRequest) {
                xmlhttp = new XMLHttpRequest();
            } else {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }

            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    return xmlhttp.responseText;
                }
            }

            xmlhttp.open("GET", myurl, true);
            xmlhttp.send();
            myValue = xmlhttp.onreadystatechange();
        };
</script>
austincheney
  • 1,189
  • 9
  • 11
  • 1
    This doesn't work in asynchronous mode. – pimvdb Sep 14 '12 at 09:56
  • If it demands a function reference to invoke the call then it should not be asynchronous to anything except perhaps the other contents of the local function. – austincheney Sep 14 '12 at 11:10
  • What do you mean? This request is asynchronous, so `return` will not return the actual response, because it has not been received yet. – pimvdb Sep 14 '12 at 14:20
  • No, its not. This is how I use AJAX in my own software at http://prettydiff.com/ Nothing in JavaScript is asynchronous. It is variant external access to JavaScript that creates the appearance of asynchronous operation. – austincheney Sep 17 '12 at 14:58
  • 2
    You really have to use synchronous mode for ajax (`.open(..., false)`) or else `return` is bogus. See your code here: http://jsfiddle.net/HApG3/. – pimvdb Sep 17 '12 at 15:22