-3

I'm looking for a way to initialize a var after an ajax call. The problem is that the ajax call is in an another file.

Here is my code :

file1.js

$(document).ready(function () {
    getKanbans();
});


function getKanbans() {
    var kanbans = RequestSender.getKanbans();
    console.log(kanbans); // print undefined
}

RequestSender.js

class RequestSender {
    static getKanbans() {
        $.ajax({
            url: './ajax/select_kanbans.php',
            type: 'GET',
            success: RequestSender.initKanbanList
        });
    }

    static initKanbanList(data) {
        var result = JSON.parse(data);
        var kanbans = [];
        for (var i = 0; i < result.kanbans.length; ++i) {
            var currentKanban = result.kanbans[i];
            kanbans.push(new Kanban(currentKanban['Name'], currentKanban['Status']))
        }
        console.log(kanbans); // correctly displayed
        return kanbans;
    }
}

I just use jQuery, all my files are included. I think that the problem come from the fact that ajax is async but I don't know how to fix that.

Martin Blondel
  • 261
  • 2
  • 9
  • Aren't you using some build tool(s) such as webpack or gulp to bundle these files into one? Alternatively, just make sure that you include the ```RequestSender``` file first? Personally I suggest you take some time to learn about tools such as webpack... Easiest solution would be to simply put them both into the same file? Basically do it manually?... – JO3-W3B-D3V Dec 18 '18 at 17:53
  • Yes i included all these files. I think the problem come from the fact that the ajax call is async – Martin Blondel Dec 18 '18 at 17:54
  • Why have it in a separate file in the first place? – liviu blidar Dec 18 '18 at 17:54
  • @MartinBlondel Have you not just tried some simple callback function? ... I mean you're already doing it with ```getKanbans```, all you need to do is pass a function into ```getKanbans```, which can then be passed on to ```initKanbanList```? Or something along those lines? I mean there's many ways to do this... – JO3-W3B-D3V Dec 18 '18 at 17:56
  • It's because my ajax call has to been in an another file (asked from my teacher). The first file is like a Controller, calling a model. Then, with the result of my RequestSender.getKanbans(), I'll call the view and edit the DOM – Martin Blondel Dec 18 '18 at 17:57

2 Answers2

0

This is called modules in javascript. You can implement them using link tags directly. But you are much better served by libraries like RequireJS and others. Then you can do things like:

require(['./RequestSender'], function (RequestSender) {
    var rs = new RequestSender();
    ... //whatever
});

Here is a good SO question that explains modules well: How do I include a JavaScript file in another JavaScript file?

Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73
0

in your example ajax call started but kanbans still undefined

function getKanbans() {
    //ajax call started but kanbans still undefined
    var kanbans = RequestSender.getKanbans();
    console.log(kanbans); // print undefined
} 

so you should complete execution after ajax call finished you can do that with the help of promises

for more information Check this

    function getKanbans(url) {
        var promiseObj = new Promise(function (resolve, reject) {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", url, true);
            xhr.send();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        console.log("xhr done successfully");
                        var response = xhr.responseText;
                        var responseJson = initKanbanList(response);
                        resolve(responseJson);
                    } else {
                        reject(xhr.status);
                        console.log("xhr failed");
                    }
                } else {
                    console.log("xhr processing going on");
                }
            }
            console.log("request sent succesfully");
        });
        return promiseObj;
    }

    function initKanbanList(data) {
        var result = JSON.parse(data);
        var kanbans = [];
        for (var i = 0; i < result.kanbans.length; ++i) {
            var currentKanban = result.kanbans[i];
            kanbans.push(new Kanban(currentKanban['Name'], currentKanban['Status']))
        }
        console.log(kanbans); // correctly displayed
        return kanbans;
    }

    $(document).ready(function () {
        // to call it 
        getKanbans('./ajax/select_kanbans.php').then(function (kanbans) {
            console.log(kanbans);
        }, function (error) {
            console.log(error);
        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Ahmed Ghoniem
  • 661
  • 1
  • 8
  • 15