简体   繁体   中英

How to return a global variable from ajax to display dhtmlx scheduler lightbox

Knothead here, with another problem. I'm working with dhtmlx scheduler and specifically with the onBeforeLightbox event. This event will return true to show the lightbox, or false otherwise. I'm trying to set up parameters whether to display the lightbox or not depending on certain conditions. But, I'm stuck with the response from the ajax request being a local variable, and out of scope within the onBeforeLightbox event. Principally I've been referring to a couple of articles: question 14220321 , and question 5316697 . I've tried using promises and callbacks, but either way am still stuck with a local variable within a success, done, or callback function. So far, the only thing that has worked has been to set async to false. I know, I know, that's bad. Here is the code I'm working on right now:

scheduler.attachEvent("onBeforeLightbox", function(event_id) {
    resp=null;
    var ev = scheduler.getEvent(event_id);
    ev.wono = orderNo;
    var id = event_id;
    var sdate = scheduler.getEvent(event_id).start_date;
    var edate = scheduler.getEvent(event_id).end_date;

    var xhr = new XMLHttpRequest();
    var url = "../php/valAppts.php";
    xhr.open("POST", url, false);
    xhr.setRequestHeader("X-INDEX", orderNo);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            resp = xhr.responseText;
        }
    }
    xhr.send();
    return resp;
});

valApps.php returns either true or false depending on the results of the sql query. How can I get xhr.responseText within the scope of the onBeforeLightbox event without having to set async to false? I imagine the solution is much simpler that it seems to me at this moment. duh!

The resp was being returned before the request was completed. You have to return the resp from the if statement like shown below.

scheduler.attachEvent("onBeforeLightbox", function(event_id) {
    resp=null;
    var ev = scheduler.getEvent(event_id);
    ev.wono = orderNo;
    var id = event_id;
    var sdate = scheduler.getEvent(event_id).start_date;
    var edate = scheduler.getEvent(event_id).end_date;

    var xhr = new XMLHttpRequest();
    var url = "../php/valAppts.php";
    xhr.open("POST", url, false);
    xhr.setRequestHeader("X-INDEX", orderNo);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        resp = xhr.responseText;
        return resp;
    }
}
xhr.send();
//    return something here.
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM