12

We are trying to implement Ajax Remote data loading in Select2:-

 $scope.configPartSelect2 =  {
        minimumInputLength: 3,
        ajax: {
            url: "/api/Part",
           // beforeSend: function (xhr) { xhr.setRequestHeader('Authorization-Token', http.defaults.headers.common['Authorization-Token']); },
          //  headers: {'Authorization-Token': http.defaults.headers.common['Authorization-Token']},
            data: function (term, page) {
                return {isStockable: true};
            },
            results: function (data, page) {
                // parse the results into the format expected by Select2.
                // since we are using custom formatting functions we do not need to alter remote JSON data
                  return { results: data };

            }
        }
    };

We are using AngularJS. With each Http request we have set it's default to have our Authtoken as header. But somehow it is not working in conjunction with Select2 Ajax request. In above code, commented code are my failed attempts.

Anand
  • 4,523
  • 10
  • 47
  • 72
  • The accepted answer might have been the only option in 2012, but today [this answer](http://stackoverflow.com/a/28793936/971557) should work for everyone. – Noel Baron Mar 01 '15 at 13:16

6 Answers6

17

Taken from select2's demo page:

Select2 will pass any options in the ajax object to jQuery's $.ajax function, or the transport function you specify.

Using JQuery 2+, I was able to successfully set OAuth 2.0 and Content-Type headers.

ajax: {
    headers: {
        "Authorization" : "Bearer "+Cookies.get('accessToken'),
        "Content-Type" : "application/json",
    },
}
Noel Baron
  • 736
  • 6
  • 17
16

This is how I fixed sending auth token. Just add this as Select2 ajax param;

transport: function(params){
    params.beforeSend = function(request){
        request.setRequestHeader("Authorization", 'OAuth ' + api_access_token);
    };
    return $.ajax(params);
},
Daantje
  • 2,406
  • 25
  • 26
7

another option:

ajax: {
    url: '/api/Part',
    params: { headers: { "Authorization": "XXX" } },
    ...
}
Lev Kazakov
  • 1,299
  • 1
  • 10
  • 8
  • Yes - [the accepted answer](https://stackoverflow.com/a/28793936/1571426) did not work for me in Select2 3.5.2, but this one did. – user9645 Sep 24 '21 at 16:27
3

I solved my above problem by supplying custom transport method.. Then I was stuck with Drop-down item not getting selected on mouse hover & drop-down item not being selected after click. After debugging I found proeprty "id" is must to have in returned json object.

Below is my code:-

    var fetchPart = function (queryParams) {

        var result = http.get(queryParams.url, queryParams.data).success(queryParams.success);

    result.abort = function() {
        return null;
    };
    return result;
};

var partFormatResult = function (part) {
    return "<div><h4>" + part.PartNumber + "</h4><p>"+ part.PartDescription + "</p></div>";
};

var partFormatSelection = function (part, container) {
    console.log(part.Id + "number - " + part.PartNumber);
    return part.PartNumber;
//    return part.PartNumber;
    //return part.Id;
};

$scope.configPartSelect2 =  {
    minimumInputLength: 3,
    ajax: {
        url: "/api/Part",
        data: function (term, page) {
            return { params: { isStockable: true, query: term, pageNo: page } };
        },
        transport: fetchPart,
        results: function (data, page) {
            console.log("result is called by select2");
            var more = (page * 10) <= data.length; // whether or not there are more results available
            return { results: data, more: more };
        }
    },
    formatResult: partFormatResult,
    formatSelection: partFormatSelection,
    dropdownCssClass: "bigdrop" // apply css that makes the dropdown taller
};
Anand
  • 4,523
  • 10
  • 47
  • 72
1

You can do like this:

transport: function (params, success, failure) {

    params.beforeSend = function (request) {
        request.setRequestHeader("Authorization-Token", http.defaults.headers.common['Authorization-Token']);
    };
    var $request = $.ajax(params);

    $request.then(success);
    $request.fail(failure);

    return $request;
}
Alexandre N.
  • 2,594
  • 2
  • 28
  • 32
0

Aanother simple option:

ajax: {
    beforeSend: function (request) {
        request.setRequestHeader("X-CSRF-TOKEN", csrf_token);
    },
}
  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Feb 24 '22 at 22:32