select2 with ajax post method
Asked Answered
I

4

15

I am trying to use select2 with ajax loading.

Here is my code:

clonedTemplate.find('[id^=detailsPhaseFinanceMinor_]').select2({
    placeholder: "Select",
    minimumInputLength: 1,
    ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        url: "mapBasic.aspx/GetFinSys",
        dataType: 'json',
        data: function (term, page) {
            return "{'term':\"" + term + "\"}";
        },
        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.Value };
        }
    }
});

The ajax call is to a webmethod/pagemethod in the code-behind of the same page:

[WebMethod]
    public static List<LookupCodeItem> GetFinSys(string term)
    {
        string stringToCompareTo = term.ToLower();

        List<LookupCodeItem> result = new List<LookupCodeItem>();


        // FIN SYS
        using (mapEntities db = new mapEntities())
        {
            List<MPO_FINSYS_AMT> finSysCodes = (from x in db.MPO_FINSYS_AMT
                                                select x).ToList();

            foreach (MPO_FINSYS_AMT item in finSysCodes)
            {
                string valKey = string.Format("{0}.{1}.{2}", item.FY, item.MDOT_MPO_CD, item.FIN_SYS);
                LookupCodeItem x = new LookupCodeItem();
                x.Value = valKey;
                x.ShortDescription = string.Format("{0}.{1}.{2}", item.FY, item.MDOT_MPO_CD, item.FIN_SYS); ;
                x.LongDescription = string.Empty;
                result.Add(x);

            }
        }

        return result;
    }

When entering data into the textbox, the POST request is made, and the json is sends appears to be properly formatted.

However, the response from the pagemethod is the entire html page. It is my understanding that this can occur with post methods if you do not have your "contentType" properly set in the ajax call. I have set it that same as all my other ajax calls that do work on the page (they are not using select2).

Does select2 ignore the "contentType" attribute? Or is there something else I've done incorrectly?

** EDIT ** After posting this, I found this issue listed at select2's github site: Issue 492 - Add Support for contentType to Ajax

It appears that it doesn't pass contentType through. Am I able to bypass selet2's built in ajax helper and use my own manually defined one?

Impertinent answered 18/1, 2013 at 16:26 Comment(1)
I think it is pretty much same as the jquery $.ajax() . You should try the Jquery documentation if it helps.Polytypic
M
4

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",
   }
   ...
}
Mandamus answered 13/1, 2016 at 11:14 Comment(0)
B
2

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

Bezanson answered 17/9, 2021 at 8:45 Comment(0)
M
1

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.

Mortonmortuary answered 20/4, 2017 at 19:35 Comment(0)
R
-7

I would suggest using WebApi or ServiceStack for your data calls instead of [webmethod].

Rockwood answered 4/5, 2013 at 13:33 Comment(2)
That is a recommendation which should be put on comments, not in an answer.Also, how would changing programming techniques help the OP, really?Giannini
Was just trying to get the poster an easy suggested/supported way to fix. Seeing as this was done 7 months ago, not much I can do about it now! :-)Rockwood

© 2022 - 2024 — McMap. All rights reserved.