Search code examples
javascripthttprequestresponse

How to call a callback method after HTTP request


My code is running inside a main function. One part of my code is to make an HTTP request with an parameter which was defined before in the function and than write the response in to a new variable and work with it later.

I would like to exclude these steps with HTTP Request outside of the main function, and just CALL the function and write the response in a variable.

Unfortunately I tried it, but it doesn't work.

Error: variable is undefined

My code:

function DoWork() {
    //some code

    var strResponseHttpRequest;
    strResponseHttpRequest = HttpRequest(strInput, function(strInput) {
    console.log(strInput);
    };

    //continue working with the variable 'strResponseHttpRequest'   
    //rest of my code
}


function HttpRequest(strInput, callBackMethod) {

    var objRequest = new XMLHttpRequest(); //New request object

    objRequest.onreadystatechange = function() {

    // Waits for correct readyState && status
    if (objRequest.readyState == 4 && objRequest.status == 200) callBackMethod(objRequest.responseText)
    }

    objRequest.open("get", "php/get-content.php?ID=" + strInput, true);
    objRequest.send();
}

I hope you can help me to find out, where the issue is. If there are some better way to do this, let me know. I would be appreciate it. Thank you.


Solution

  • Do you mean an asynchronous callback? You'll want to wait until the server gives back the correct status and readyState.

    Change this:

    objRequest.onload = function() { var strResponse = this.responseText; return strResponse; };

    To this:

    objRequest.onreadystatechange = function() {
    
        // Waits for correct readyState && status
        if (objRequest.readyState == 4 && objRequest.status == 200) callBackMethod(objRequest.responseText);
     };`
    

    and pass in a callback method as a second parameter to HttpRequest(strInput, callbackMethod) like so:

    strResponseHttpRequest = HttpRequest(strInput, function(responseText) {
        console.log(responseText);
    });
    

    Also add callbackMethod as a parameter like so:

    HttpRequest(strInput, callbackMethod)