JQuery Select2 Ajax with preload data

I am using jQuery Select 2 plugin . With the settings that I use, I allow the "Multiple" selection from the Ajax answer that is associated with my employee database. In essence, this allows me to select multiple employees. Then I can save the data and iterate over the parameters and save them in the database.

The problem I am facing is when I return to this page to now β€œedit” the information, I preload the users that I selected earlier, but ALSO must support AJAX to find additional employees.

Has anyone done something similar or knew about a possible job?

//Build preset carpool members
    <?php $counter = 1; foreach($fetchData->data as $data){ ?>

        var preload_data<?php echo $counter;?> = [

            <?php foreach($data->carpool->employees as $dataCP){ 
                $result .= "{ id: '".$dataCP->empID."', text: '".$dataCP->LastName.", ".$dataCP->FirstName."'},";
            } 
            echo rtrim($result, ',');
            ?>

            ];

         $('#carpool<?php echo $counter; ?>').select2({
                multiple: true,
                query: function (query){
                    var data = {results: []};

                    $.each(preload_data<?php echo $counter; ?>, function(){
                        if(query.term.length == 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0 ){
                            data.results.push({id: this.id, text: this.text });
                        }
                    });

                    query.callback(data);
                },
                ajax: { 
                    url: "jsonUser.php",
                    dataType: 'json',
                    data: function (term) {
                        return {
                            term: term, // search term
                        };
                    },
                    results: function (data) { // parse the results into the format expected by Select2.
                        return {results: data};
                    }
                },
            });

        $('#carpool<?php echo $counter; ?>').select2('data', preload_data<?php echo $counter; ?> )




    <?php $counter++; } ?>

select2 . ajax , .

, - ?

+4

Source: https://habr.com/ru/post/1543278/


All Articles