0

I have to develop a part of my project in javascript, which really isn't a language I feel confortable with.

Anyway, here's my problem : I have to work with the (json) data I get from the 'php/get_services_list.php' program (which is working well). So I am trying to store the data in my 'services' variable, but 'services' is destroyed as soon as I leave the getJson block

-> the first console.log(services); displays the json array, as expected

-> the second one just displays 'undefined', and of course I've got an error later when I try to evaluate services.length.

So yeah, I really need to be able to work with the data outside the $.getJSON block. Thanks in advance for your advices !

function addServiceInput() {
    var services;
    $.getJSON("php/get_services_list.php").done(function(data) {
        services = data;
        console.log(services);
    });
    console.log(services);

    var select = "<select class='col-lg-3' name='service'>";
    for (let i = 0; i < services.length; i++) {
        select += "<option value='" + services[i] + "'>" + services[i] + "</option>";
    }

    select += "</select>";
    return select;
}
  • 4
    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) – nicholaswmin Jan 29 '19 at 11:17
  • 1
    its because ajax call are asnychronous and does not wait for your next code block. So in result var select and for are evulated earlier than ajax response and done method. – daremachine Jan 29 '19 at 11:19
  • Ok I've just understood the problem, so how can I wait for the ajax block to be over ? Or how do I make a synchrone call to my program ? – MatthiasWustmann Jan 29 '19 at 11:32
  • You learn how to manage async code from the duplicate question we posted. – nicholaswmin Jan 29 '19 at 11:35

0 Answers0