Skip to content Skip to sidebar Skip to footer

Returning Xmlhttp Responsetext From Function As Return

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 : &l

Solution 1:

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.

functionloadXMLDoc(myurl, cb) 
{
   // Fallback to Microsoft.XMLHTTP if XMLHttpRequest does not exist.var xhr = (window.XMLHttpRequest ? newXMLHttpRequest() : newActiveXObject("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
});

Solution 2:

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

Returning a value:

<script>functionloadXMLDoc(myurl) {
        var xmlhttp;
        if (window.XMLHttpRequest) {
            xmlhttp = newXMLHttpRequest();
        } else {
            xmlhttp = newActiveXObject("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 = newXMLHttpRequest();
            } else {
                xmlhttp = newActiveXObject("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>

Post a Comment for "Returning Xmlhttp Responsetext From Function As Return"