简体   繁体   中英

Populate a Select2 Tag input field with data from an AJAX request using X-editable jQuery library

I am in desperate need of some help from JavaScript experts. I have spent the last 7 hours trying hundreds of combinations of code to get a basic Tag selection input field to work with the library x-editable and select2 .

I am building a Project Management app which is going to have Project Task data shown in a popup Modal Div. In the Task Modal, all Task fields will be editable with in-line edit-in-place capability using AJAX.

I am using:

I have setup a basic JSFiddle demo to experiment with just for this StackOverflow question. I don't have the thousands of lines of code from my actual application , however I do have majority of the 3rd part libraries that are being used included into the page. THe reason is to make sure that none of them are interfering with the results.

JSFiddle Demo: http://jsfiddle.net/jasondavis/Lusbqfhs/

The Goal:

  • Setup X-editable and Select2 on a Field to allow users to select and enter in Tags for a Project Task.
  • Fetch available Tag records from a backend server which will return a JSON response with Tag ID number and Tag Name and use this data to populate the Selection2 input field to allow a user to select multiple Tags.
  • Allow user to also type in a NEW tag and it will post and save the new Tags to the backend as well!
  • When tags are selected and the save button is clicked, it will save the list of selected Tags bu ID number back to a database.

Problems:

Now I have tried hundreds of variations of options and code combinations from my research in the past 7 hours. I cannot seem to get this basic functionality to work and majority of the examples I have found do not seem to work correctly anymore!

On this demo page for the library x-editable http://vitalets.github.io/x-editable/demo-plain.html?c=inline near the bottom of the examples in the table where it says Select2 (tags mode) that functionality is what I need! I just need it to load the available tags from an AJAX request and all the docs claim it can do this with no problem at all!

This is the Documentation section from X-Editable for Select2 fields - http://vitalets.github.io/x-editable/docs.html#select2

It also links to the Select2 documentation and claims that all the Options in Select2 can be set and used as well located here - https://select2.github.io/options.html

I use MockAjax library to simulate an AJAX response in pages like JSFiddle for testing. In my JSFiddle demo here http://jsfiddle.net/jasondavis/Lusbqfhs/ I have 2 MockAjax responses set up....

$.mockjax({
    url: '/getTaskTags',
    responseTime: 400,
    response: function(settings) {
        this.responseText = [
            {id: 1, text: 'user1'},
            {id: 2, text: 'user2'},
            {id: 3, text: 'user3'},
            {id: 4, text: 'user4'},
            {id: 5, text: 'user5'},
            {id: 6, text: 'user6'}
        ];
    }
});

$.mockjax({
    url: '/getTaskTagById',
    responseTime: 400,
    response: function(settings) {
        this.responseText = [
            {id: 1, text: 'user1'},
            {id: 2, text: 'user2'},
            {id: 3, text: 'user3'},
            {id: 4, text: 'user4'},
            {id: 5, text: 'user5'},
            {id: 6, text: 'user6'}
        ];
    }
});

They both are supposed to return a Mock JSON string for my Selection list to be populated with.

Here is my code for the demo...

$(function(){

    //remote source (advanced)
    $('#task-tags').editable({
        mode: 'inline',
        select2: {
            width: '192px',
            placeholder: 'Select Country',
            allowClear: true,
            //minimumInputLength: 1,
            id: function (item) {
                return item.CountryId;
            },
            // Get list of Tags from AJAX request
            ajax: {
                url: '/getTaskTags',
                type: 'post',
                dataType: 'json',
                data: function (term, page) {
                    return { query: term };
                },
                results: function (data, page) {
                    return { results: data };
                }
            },
            formatResult: function (item) {
                return item.TagName;
            },
            formatSelection: function (item) {
                return item.TagName;
            },
            initSelection: function (element, callback) {
                return $.get('/getTaskTagById', { 
                    query: element.val()
                }, function (data) {
                    callback(data);
                });
            } 
        } 
    });


});

Now in the demo when you click the field to select Tags, it just keeps "loading" and never gets a result. Looking at the Console, it seems my MockAjax request is not working, however the 2nd one is working so I am not sure what is wrong with my AJAX request?

I could really use some help if someone can help to get this to work I would be very greatful, I have spent my whole night without sleep and am not even any closer to a working solution! Please help me!

Thank you

X-Editable uses Select2 3.5.2 which doesn't use jQuery.ajax() directly. It has its own ajax function and calls jQuery.ajax() like that:

transport = options.transport || $.fn.select2.ajaxDefaults.transport
...
handler = transport.call(self, params);

That's why $.mockjax({url: '/getTaskTags'... does not work.

To get it work you need to create your own transport function, something like that:

var transport = function (queryParams) {
    return $.ajax(queryParams);
};

and set the transport option:

   ajax: {
            url: '/getTaskTags',
=> transport: transport,
            type: 'post',
            dataType: 'json',
            data: function (term, page) {
                return { query: term };
            },
            results: function (data, page) {
                return { results: data };
            }
        },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM