Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Custom Headers to Ajax request on Select2

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.

like image 760
Anand Avatar asked Oct 30 '12 07:10

Anand


People also ask

What is request header in Ajax?

The headers are additional key-value pairs send along with ajax request using the XMLHttpRequest object. An asynchronous HTTP request to the server by using The ajax() function and by including the header it describes to the server what kind of response it accept.

How do I add options in Select2?

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).

What does Select2 () do?

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.


1 Answers

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",
    },
}
like image 118
Noel Baron Avatar answered Sep 25 '22 02:09

Noel Baron