jquery - Select2 load data with Ajax from file -
i have script called listofvalues.php, queries database , returns json format values.
what need pass these values select2 data member. need load once. 
i don't need pass values select2 input (term) listofvalues.php described in this example
$('#select2div').select2({         //data:[],     ajax: {         datatype: "json",         url: "listofvalues.php",             success: function (data) {                   }     }   can me this?
simple example
it useful know format of object you're getting listofvalues.php, let's assume, sake of simplicity looks this:
[ {"id": 1, "text": "option1"},   {"id": 2, "text": "option2"},   {"id": 3, "text": "option3"} ]   this easiest format use, default, select2 can handle objects property names id , text , render them dropdown list. select2 initialisation might this:
$('#select2div').select2({     ajax: {         datatype: "json",         url: "listofvalues.php",         results: function (data) {             return {results: data};         }     } });   slightly trickier example
now let's assume data listofvalues.php doesn't follow convenient naming conventions:
[ {"id": 1, "firstname": "john", "lastname": "lennon"},   {"id": 2, "firstname": "paul", "lastname": "mccartney"},   {"id": 3, "firstname": "george", "lastname": "harrison"},   {"id": 4, "firstname": "ringo", "lastname": "starr"} ]   we'll have set function handle output:
function formatvalues(data) {     return data.firstname + ' ' + data.lastname; }   and our select2 initialisation:
$('#select2div').select2({     ajax: {         datatype: "json",         url: "listofvalues.php",         results: function (data) {             return {results: data};         }     },     formatresult: formatvalues });   let me know how on.
Comments
Post a Comment