It's not removing everything, the JSON request is just not finished when you do items += "</select>";
!
$.getJSON
runs asynchronously, meaning that the statement starts the request to the given URL, but it doesn't wait for the answer, the program flow then just continues on with the next statement (in your case the items += ...
, without waiting for $.getJSON
to finish! Only when the response arrives, the given success function is called.
You have two choices in how to solve that problem.
Alternative 1 would be postponing all the assemblage of the items
string until $.getJSON
has succeeded:
$.getJSON("https://dev.xxx.com",
function(data){
var items = "<select id=\"orderer_search\" name=\"search\">";
$.each(data, function(index,item) {
items += "<option value='" + item + "'>" + item + "</option>";
});
items += "</select>";
alert(items); // or whatever else you have to do with items
}
);
Alternative 2 would be to make the $.getJSON
call non-asynchronous, so that the function waits for the response to come. You'd have to use the $.ajax
function, like this:
var items = "<select id=\"orderer_search\" name=\"search\">";
$.ajax({
url: "https://dev.webshop.restore.net.au/_pag/shop/TEST/?
bc=TEST&sec=order%2F&pag=get_orderers_list",
dataType: 'json',
async: false,
success: function(data) {
$.each(data, function(index,item) {
items += "<option value='" + item + "'>" + item + "</option>";
}
}
});
items += "</select>";
alert(items); // or whatever else you have to do with items
Alternative 1 has the potential to make your script more responsive, if there is anything else to do apart from filling this select; because then the request is running in the background, quasi in parallel to your other code. So I would usually go for that.