-1

I want to return response data when XMLHttpRequest transaction completes successfully. upon calling my function trashAnswer() to a variable I expect to assign the value returned to the variable and do something with it like below:

I can see resData is always undefined when i try to access data from it. Please how can I solve this?

var resData = trashAnswer({answerid:58,answererid:65,questionid:458});

This is the code:

//This function will trash answer object
function trashAnswer(param){
    if (typeof param !== 'object' || param == null ) {
        throw "trashAnswer(): Strictly expect valid object.";
    }

    var param = $.extend({answerid:0,answererid:0},param),
            fd    = new FormData();
                            fd.append('answerData',JSON.stringify(param));
                            fd.append('trash-answer',true);

    var req = AJAX_REQEUST_OB();
    req.open(bigPipe.formMethod.a,ajax.ac,true);
    req.onload = function(){
        if (req.readyState === req.DONE && req.status === 200) {
           //ParseJSON is a custom function to check if response is a valid JSON...if its valid then then function will return response Data else return false
            var Data = ParseJSON(req.responseText); 
            //process data...
            var EvalData = !Data ? function(){
                throw "Invalid JSON";
            }:function(Data){
                //do something...
                return Data;
            };
            //call EvalData ****method
            EvalData(Data);
        }

    }

    //send request.
    req.send(fd);
}
james Oduro
  • 673
  • 1
  • 6
  • 22
  • AJAX = Asynchronous JavaScript And XML. it's `Asynchronous`, so you can't do something like `var resData = ajaxFunction()` use `Promise` or `await/async`. – Hank X Nov 20 '19 at 07:46
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – StudioTime Nov 20 '19 at 08:56

1 Answers1

1

This is an asynchronous call. When you do trashAnswer({...}); you are triggering the request and your code continues to execute. At some point in the future your request may work. Here the "may" part is important: your request may fail for several reasons, but you are only checking the HTTP status 200, that is an "OK" response).

An easy solution:

var resData;
trashAnswer({answerid:58,answererid:65,questionid:458});

//This function will trash answer object
function trashAnswer(param){
    // ...
    req.onload = function(){
        if (req.readyState === req.DONE && req.status === 200) {
            // ...
            // in your "//do something...":
            resData = // your result here. If you do not have a local variable,
                      // it will change the global one (not recommended, see comment below)
        }
    }
    // ...
}

Your solution is even better if you avoid using a global variable (See here why). But I believe this is a good starting point for you to understand how async calls work.

You can also use promises (including the async/await syntax). A good start reading about how this works is https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

saulotoledo
  • 1,737
  • 3
  • 19
  • 36