Can someone please tell me why this isn’t working?
var items = "<select id=\"orderer_search\" name=\"search\">";
$.getJSON("https://dev.xxx.com",
function(data){
$.each(data, function(index,item) {
items += "<option value='" + item + "'>" + item + "</option>";
});
});
items += "</select>";
If I place an alert(items) before:
items += "</select>";
The value is:
<select id="orderer_search" name="search">
But if I place an alert in the each loop, each popup is showing the value that has come back from the JSON request.
It is almost like as soon as the each loop is over, it is removing everything I added to the items variable during the each loop. I am new to JQuery so I’m sure it’s something simple.
It’s not removing everything, the JSON request is just not finished when you do
items += "</select>";!$.getJSONruns 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 theitems += ..., without waiting for$.getJSONto 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
itemsstring until$.getJSONhas succeeded:Alternative 2 would be to make the
$.getJSONcall non-asynchronous, so that the function waits for the response to come. You’d have to use the$.ajaxfunction, like this: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.