Select2 and initSelection callback
Asked Answered
F

2

29

On page load, I'm trying to use initSelection to select ID 60 (specified value of the input field). I can't seem to get it to work properly.

The PHP scripts work great and return the correct values, but how do I get the JS to do the callback correctly?

JavaScript:

$(document).ready(function() {
    $('#editAlbumArtistId').select2({
            placeholder: 'Search names',
            ajax: {
                url: "/jQueryScripts/jQuerySelectListArtists.php",
                dataType: 'json',
                quietMillis: 100,
                data: function (term, page) {
                    return {
                        term: term, //search term
                        page_limit: 10 // page size
                    };
                },
                results: function (data, page) {
                    return {results: data.results};
                }

            },
            initSelection: function(element, callback) {

            var id = $(element).val();
            if(id !== "") {
                $.ajax("/jQueryScripts/jQuerySelectListArtists.php", {
                    data: {id: id},
                    dataType: "json"
                }).done(function(data) {
                    callback(data);
                });
            }
        }
    });
});

HTML:

<p>
    <input type='hidden' value="60" data-init-text='Search names' name='editAlbumArtistId' id='editAlbumArtistId' style="width:180px;"/>
</p>

Every time I refresh the page, I see that the PHP script gets executed and that it returns the proper ID and text. However, the field isn't updated and I've seriously tried everything I can think of.

I'm using Select2 3.4.3.

Any help would be greatly appreciated.

Fauver answered 19/9, 2013 at 20:17 Comment(4)
Have you tried inspecting what happens in developer tools? See if your ajax call is returning a 200, and that the the json has a key of results in it.Papaya
You should use ajax settings ( success , error, complete ). api.jquery.com/jQuery.ajax/#jQuery-ajax-settingsSholokhov
Why are you putting jsonp as datatype?Simulation
Thanks for the comments so far! I've changed datatype to json from jsonp (didn't know the difference, sorry). I now get "undefined" upon load. I've tried using ajax success, same results. @Papaya the ajax is returning 200. The ajax is indeed returning results.Fauver
F
46

Finally solved it! I figured select2 didn't want an array since it's a single value, so I selected the first element of the data.results array.

callback(data.results[0]);

And if you have set multiple:true, just accept the entire results array;

callback(data.results);
Fauver answered 20/9, 2013 at 6:3 Comment(4)
How do you know this? i got mad because this problem and work 3 days! Finally find you awesome answer!!!Graveyard
@mad-marvin It would have been better if you /someone had provided the object structure . Coz its not always obvious about what data or data.results or even data.results[0] contains. I am still looking at select2 code and update here if I find something.Rittenhouse
Just updated the answer itself. I hope it helps and do not mess up with the actual answer.Rittenhouse
it depends on your remote result. If you result looks like [{...}, {...}], then data[0] is just fine. Mad Marvins result looks probably somehow like this: {"results": [{...}, {...}]}Murr
L
3

You could also use this for less code:

    initSelection: function(element, callback) {
        return $.getJSON("/jQueryScripts/jQuerySelectListArtists.php?id=" + element.val(), null, function(data) {
            return callback(data[0]);
        });
    }

I saw this example in the Select2 wiki, but i had to deal with callback(data) vs callback(data[0]) like you did.

Levy answered 20/5, 2014 at 14:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.