Search code examples
javascriptajaxcallbackxmlhttprequest

Change callback function name


Hi so i have these two functions which get() is a custom ajax request function and you can see that it has two parameters url works fine but the func one which is the callback doesn't seem to change func(serverResponse); to what document.write(serverResponse);. So I was wondering what on earth am I doing wrong? It would be great if one of the kind developers on StackOverflow could help me out really soon. Thank you so much :)

function get(url, func) {
            var xhReq = new XMLHttpRequest();
            xhReq.open("GET", url, false);
            xhReq.send(null);
            var serverResponse = xhReq.responseText;
            func(serverResponse); // Shows "15"
        }

        get('ip.php', 'document.write');

Solution

  • get('ip.php', 'document.write');
    

    should be:

    get('ip.php', document.write.bind(document));
    

    The former passes a string; the latter passes a function.

    Perhaps a more typical way to do this sort of thing:

    get('ip.php', function (text) {
        document.write(text);
    });