select2 with ajax post method select2 with ajax post method ajax ajax

select2 with ajax post method


I was have same problem and below solution works for me:

ajax: {   ...   params: { // extra parameters that will be passed to ajax        contentType: "application/json; charset=utf-8",   }   ...}


Don't forget to add the CSRF token to your post request. It may be that you do everything right on the client side, but the server refuses the request, because it is missing the token. See for instance for the PHP Laravel Framework: https://laravel.com/docs/5.4/csrf#csrf-x-csrf-token for more info.


This worked for me:

 $(document).ready(function () {        $('.js-example-basic-single').select2({            minimumInputLength: 2,            ajax: {                url: "your api endpoint",                dataType: 'json',                contentType:"application/json; charset=utf-8",                type: "POST",                data: function (term) {                    return (JSON.stringify({ searchString: term.term }))                }            }        });        });

html :https://select2.org/getting-started/basic-usage