0

I dynamically make a -tag with JQuery. The options are made from a map I create with several ajax calls. When I visit the page the first time, it does have a select-tag but no options. However the second time I visit the page, the page has the options. So there is a delay, however when I put a console.log(map) in the function that creates the select-tag, it does display all the options.

Here is my code to create the select tags:

var namefield = $('<select></select>').attr("id","name");
    getmapofpeoplefromindex(index); // this creates the map with 3 AJAX-calls
    map.forEach(function(key,value){
        namefield.append($("<option>").attr('value',value).text(key));
    });

What is going wrong and how can I make sure I have a filled-in selectbox?

fangio
  • 1,746
  • 5
  • 28
  • 52
  • I think, there is a problem in your getmapofpeoplefromindex(index); and I see another problem map.forEach(function(key,value) - this code should look like map.forEach(function(value,key){ }) – Slawa Eremin Apr 25 '17 at 20:31
  • @SlawaEremkin getmapofpeoplefromindex(index) works and the mapping function as well. Because the second time it works... getmapofpeoplefromindex(index) does a few ajaxcalls and then makes a map and stores it in a global variable. – fangio Apr 25 '17 at 20:35
  • As your function depends on Ajax calls, the result from those requests will only become available asynchronously, but you are expecting the result (i.e. *map*) to be there *synchronously*. Obviously that is not the case. See [How do I return the result from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). – trincot Apr 25 '17 at 20:40
  • @trincot the first comment says do not use async:false but this works for me, should I look for something else or leave it that way? however, thank you for the insight of asynchronous calls, I did not know that. – fangio Apr 25 '17 at 20:46
  • `async:false` is deprecated, and while some browsers may still support it, others ignore it, and so you might be mislead that it works, while in fact it just ignores that setting and runs asynchronously, which would explain your problems. Also be aware that `console.log` is not reliable to know what an object contained at the time of the logging, since many browsers implement `console.log` to just keep the object reference and do the retrieval of it later (when the content might in the mean time be loaded into it). – trincot Apr 25 '17 at 20:56
  • what can I do instead of async:false? – fangio Apr 25 '17 at 21:02

0 Answers0