-2

What I don't understand is when a ajax request, when you call the done function it should be done right? Well I don't get the values until I use a set timeOut then I get my results, why?? I dont get it!!

{"status":"1","msg":"Return Successful","callbackFunct":"LinkMenu.setMenuItems()","return":[{"name":"save","image":"","action":"","status":""},{"name":"back","image":"","action":"","status":""},{"name":"delete","image":"","action":"","status":""}]}

class ServerQuery {

constructor(request, level) {
    console.log("Server query started, " + request + " " + level );
    this.lev = level;
    this.file = "http://" + location.hostname + "/" + this.lev + "/" + request;
    this.values = new Object();
    this.data   = new Array();
    this.result      = null;
    this.setRequiredValues();
}

setRequiredValues() {
    console.log("Setting required Values");
        let ses = document.getElementById("key").value;
        let orgid = document.getElementById("OrgId").value;
        let userid = document.getElementById("userid").value;            
        this.values['key'] = ses;
        this.values['orgid'] = orgid;
        this.values['userid'] = userid;
        console.log("Required Values loaded: " + JSON.stringify(this.values));           
}

addValue(key, insert) {
    console.log("adding Values " + key + " " + JSON.stringify(insert));
    this.r = new Object();
    this.r[key] = insert;
    this.data.push(this.r);
    console.log("Values Added " + JSON.stringify(this.data));              
}

// select this method to trigger a return callback
sendRequest() {
    console.log("Server Query sending Request");
    connect_ajax();

    // this.values is an object
    this.values['linked'] = this.data;
    let req = JSON.stringify(this.values);
    let uandp = "requesting=" + req;
        console.log("Data adding " + uandp);
        $.post(this.file, uandp)
            .done(function done2(result) {
                console.log("server query finsihed with this result " + result);
                this.r = JSON.parse(result);
                if (this.r.status == 1) {
                    console.log("ServerQuery after parse " + this.r);
                    console.log("output " + this.r.callbackFunct);
                    if (typeof this.r.callbackFunct != 'undefined') {
                        setTimeout(function() {
                            this.r.callbackFunct(this.r.callbackVars);
                        }, 500);
                    } else {
                        alert("Callback Not set");
                    }
                }
                else if (this.r.status == 3) {
                    alert(this.r.msg);
                }
            })
            .fail(function processFailed() {
                console.log("an Error has occured");
            })
            .always(function processAlways() {
                console.log("Finished");
            });
        console.log("Requesting url " + this.file);

}   

// select this method to get a static response from server
callRequest() {
    console.log("starting serverquery process() ");
    let answer = this.process();
    console.log("process returned " + answer);
    return answer;

}

process() {
    this.values['linked'] = this.data;
    let req = JSON.stringify(this.values);
    let uandp = "requesting=" + req;
    let file = this.file;
        console.log("Data adding " + uandp);
    let return_first = function () {
    let tmp = null;
    $.ajax({
        'async': false,
        'type': "POST",
        'global': false,
        'dataType': 'html',
        'url': file,
        'data': uandp,
        'success': function (data) {
            tmp = data;
        }
    });
    return tmp;
    }();
    return return_first;
}

cleanUp() {
    delete this.file;
    delete this.values          
    console.log("removed values from global " + this.values);
    console.log("removed file from global " + this.file);
}  
}
  • Try (a) Formatting your code properly (your indentation is off so bits of it aren't marked as code and other bits of it aren't clear) (b) Providing a [mcve] (you've got two different Ajax calls in this and I'm not entirely sure which ones you are talking about, focus on **minimal**) and (c) describing exactly where things are breaking, what output you expect and what output you get (you have lots of console.log statements, what do they say and what do you expect them to say)? – Quentin Dec 07 '16 at 21:59
  • `.fail(function processFailed() { console.log("an Error has occured"); })` does this code works? – demo Dec 07 '16 at 22:02
  • In case you already use jquery, I think it will be easier to use it everywhere – demo Dec 07 '16 at 22:06

1 Answers1

-1

The reason why is because a method returns even though you have the asynchronous $.post call still being executed (i.e. it hasn't returned yet). So I believe you are seeing something that you are not expecting.

If you invoke a function (let's call it ProcessResult) that you passed in, then you can have that ProcessResult function be called once the $.post done is called.

sendRequest(caller, myDelegateFunction) {
    $.post(this.file, uandp)
            .done(function done2(result) {
                // this invokes a function and passes in result as a parameter.
                myDelegateFunction.call(caller, result);
            });
}

// now you can call this like this:
function ProcessResult(result) {
   console.log(result);
}
sendRequest(this, Hello); // invoke sendRequest function, and pass in 'this' and 'Hello' function.

// or like this:
sendRequest(this, function(result) {
   console.log(result);
});
AlvinfromDiaspar
  • 6,611
  • 13
  • 75
  • 140