I am using bootbox prompt with select. To build the option for the select you have to provide something like this:
inputOptions: [
{
text: 'Ad inizio tabella',
value: '',
},
{
text: 'Choice One',
value: '1',
},
{
text: 'Choice Two',
value: '2',
},
{
text: 'Choice Three',
value: '3',
}
]
I want to make the options variable fetching them from the database. So I built a function:
$.getJSON( "get_fields.php", { wizard: wizard } ).done(function(data){fields_selected=data;});
that returns a JSON as expected:
[
{
"text":"Inserisci dopo Nome",
"value":"Nome"
},
{
"text":"Inserisci dopo cognome",
"value":"cognome"
}
]
To pass it to the bootbox function I tried to do:
var fields = '';
$.getJSON( "get_fields.php", { wizard: wizard } ).done(function(data){fields_selected=data;});
bootbox.prompt({
title: "Scegli dopo quale campo inserire il nuovo",
inputType: 'select',
inputOptions: fields,
callback: function (result) {
but in both cases I get the following:
Uncaught Error: Error: prompt with select requires options
since fields remains empty.
What am I missing to be able to inject the data coming from getJson?
2
Answers
Because $.getJSON is an asynchronous call and returns a promise you cannot use directly without resolving it.
Therefore you can use bootbox.init callback in order to init your select box:
Since
$.getJSON
is an AJAX call, your options won’t exist until that resolves. jQuery AJAX functions are non-blocking, so you’re creating a Bootbox prompt with an "empty" object.The easiest fix is to create the prompt in the success callback of your AJAX function. Something like: