Home > Back-end >  URL is updating but Ajax call still going to old one
URL is updating but Ajax call still going to old one

Time:09-05

I am editing someone else project and they have used a lot of DOM which I'm not familiar with.

First select box

<select name="task_projectid" id="task_projectid"
 data-assigned-dropdown="assigned"
 data-ajax--url="/feed/projects?ref=general"></select>

When user select project I'm using following to update the data-ajax--url in task_itemid

$(document).on('change', '#task_projectid', function() {
  $('#task_itemid').attr('data-ajax--url', '/feed/items?ref='   this.value);
});

here is task_itemid box

<select name="task_itemid" id="task_itemid" 
data-assigned-dropdown="assigned" 
data-ajax--url="/feed/items?ref=">
</select>

It's working and url on task_itemid changed to

/feed/items?ref=4

But the Ajax call still going to

/feed/items?ref=

Please help.

I found this

$(".js-select2-basic-search-modal").select2({
        theme: "bootstrap",
        width: null,
        containerCssClass: ':all:',
        minimumInputLength: 1,
        minimumResultsForSearch: 1,
        ajax: {
            dataType: "json",
            type: "GET",
            data: function (params) {
                var queryParameters = {
                    term: params.term
                }
                return queryParameters;
            },
            processResults: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return {
                            text: item.value,
                            id: item.id
                        }
                    })
                };
            }
        }
    });

CodePudding user response:

See the documentation:

It is recommended that you declare your configuration options by passing in an object when initializing Select2. However, you may also define your configuration options by using the HTML5 data-* attributes, which will override any options set when initializing Select2 and any defaults.

You're changing the attribute, but by that time Select2 has already been initialised and read the old value.

I think you can use the dynamic urls feature to read the value when the Ajax request is triggered.

ajax: {
    url: () => $('#task_itemid').attr('data-ajax--url'),

I haven't tested this, and it might override the logic for adding a query string to the URL, in which case you'll need to make that function add the data from params.term too.

  • Related