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?
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
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",
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With