returning xmlhttp responseText from function as return [duplicate]
Asked Answered
A

2

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>
Astatic answered 14/9, 2012 at 9:37 Comment(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).Nectareous
M
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
});
Missie answered 14/9, 2012 at 9:48 Comment(6)
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?Astatic
@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.Missie
my goal is using asynronous mode, so i must create handler to pass the response text?Astatic
why your code cannot run? even im using alert() function when i call it does't return anythingAstatic
@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.Missie
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?Astatic
C
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>
Contemporize answered 14/9, 2012 at 9:46 Comment(5)
This doesn't work in asynchronous mode.Genevieve
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.Contemporize
What do you mean? This request is asynchronous, so return will not return the actual response, because it has not been received yet.Genevieve
No, its not. This is how I use AJAX in my own software at prettydiff.com Nothing in JavaScript is asynchronous. It is variant external access to JavaScript that creates the appearance of asynchronous operation.Contemporize
You really have to use synchronous mode for ajax (.open(..., false)) or else return is bogus. See your code here: jsfiddle.net/HApG3.Genevieve

© 2022 - 2024 — McMap. All rights reserved.