Can I set the query string parameters in Select2 when using AJAX data source?

avatar
821    1 year ago

I am running into a "weird" (maybe not) case where I need to pass the parameters through the URL instead of send them as q. Take a look at the following example from docs:

$(".js-data-example-ajax").select2({
  ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term, // search term
        page: params.page
      };
    },
    processResults: function (data, params) {
      params.page = params.page || 1;

      return {
        results: data.items,
        pagination: {
          more: (params.page * 30) < data.total_count
        }
      };
    },
    cache: true
  },
  ...
});

In the above example params.term is sent to the server and you can use any mechanism to get it and do what you want to do.

In my case I am sending the search term to an API endpoint. The API is expecting something like the following example:

http://someurl?slug=56&title=56&description=56&content=56

In other words:

'http://someurl?slug='+params.term+'&title='+params.term+'&description='+params.term+'&content='+params.term

As you many notice params.term become the value to be sent on the URL for the API.

But I don't know how to achieve this with Select2. I have been looking for some info but without success, this is what I have been looked so far:

But none say anything about what I need. Does any have any idea in how to achieve this?

Answers { 1 }
avatar
1 year ago

Change the data object to reflect the properties you want to have in the query string:

data: function (params) {
  return {
    slug: params.term, 
    description: params.term,
    content: params.term
  };
},

Double check in dev tools network that this is indeed done as a GET otherwise try adding type:'GET' to the ajax options