2

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?

ReynierPM
  • 17,594
  • 53
  • 193
  • 363
  • Query string you want doesn't seem to match api docs https://developer.github.com/v3/search/. The `q` in your data seems correct – charlietfl Aug 06 '17 at 23:37
  • @charlietfl that's just an example, doesn't mean it's the right URL I just copied and paste from the example to keep the post on the same page, if it's confusing I can change it to something else – ReynierPM Aug 06 '17 at 23:38
  • sure it's confusing when you use query params that are made up or show an api url like github that is well documented – charlietfl Aug 06 '17 at 23:39
  • Now have no idea what relationship of the `params` in plugin are to your `slug, title, description` etc but your `data` object properties should match those property names – charlietfl Aug 06 '17 at 23:43
  • @charlietfl please re-read the post, it's better now? Let's cleanup this comments when you is satisfied with the OP :) – ReynierPM Aug 06 '17 at 23:48

1 Answers1

4

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

charlietfl
  • 170,828
  • 13
  • 121
  • 150