0

in the second block of the code, "oSearch" is set to country_of_interest. Any idea why it is taking 'test' instead of the country name?

Thanks!

$(document).ready(function () {
    var country_of_interest = 'test';

    $.ajax({
        url: "http://127.0.0.1:8000/api/users/?format=json"
    }).then(function (data) {
        country_of_interest = (data[0].country_name);
    });

    $('#posts').DataTable({
            autoWidth: true,
            responsive: true,
            "oSearch": {"sSearch": country_of_interest},
        }
    );
});
Bishonen_PL
  • 1,400
  • 4
  • 18
  • 31
  • 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) – Taplar Nov 02 '18 at 21:50
  • Because ajax is asynchronous and will not have finished by the time you execute the DataTable() execution. – Taplar Nov 02 '18 at 21:50
  • Move the DataTable() call *into* the `then()` callback – Taplar Nov 02 '18 at 21:50

1 Answers1

1

You have to move your second block of your code in to your successful callback function.

$(document).ready(function () {
    var country_of_interest = 'test';

    $.ajax({
        url: "http://127.0.0.1:8000/api/users/?format=json"
    }).then(function (data) {
        country_of_interest = (data[0].country_name);
        if(country_of_interest){
       $('#posts').DataTable({
            autoWidth: true,
            responsive: true,
            "oSearch": {"sSearch": country_of_interest},
        }
    );
   }
 });


});
Jameel Moideen
  • 7,542
  • 12
  • 51
  • 79