'select2 and axios: success is not a function
I am new to javascript, callback functions and select2. Thanks in advance for your help :)
I am looking at implementing select2 to search against an API but I will have to use axios instead of the default jQuery method. Below is my code. I am able to send and retrieve results but I am not sure how to use the success callback.
I get "TypeError: success is not a function"
$("#profile-select").select2({
ajax: {
transport: function(params, success, failure){
axios.post("/rest/vue/1.0/profile/search", {query: $("#profile-select").val()})
.then(function(response){
success(response);
})
.catch(function(error){
alert(error);
});
},
processResults: function(data){
var processedArray = [];
data.profiles.forEach(function(item){
processedArray.push({id: item.ID, text: item.name});
});
return processedArray;
}
},
minimumInputLength: 2,
placeholder: "Select a profile",
allowClear: true
});
Questions
- How do I return the response data to processResults in the .then function on the axios request? The documentation is at https://select2.org/data-sources/ajax
- What is the best way to pass the input from the select list to the post request? Currently I am using jQuery.val() function which doesn't seem to work.
Solution 1:[1]
You can create callback functions just like any other functions. For example:
function success(response) {
//do with response data what's necessary
}
Callback means that you pass this function as parameter for later execution.
When you create select2 ajax transport, then you pass your function name as parameter (as callback function). When code execution meets line "success(response);" then your success function is actually executed.
Solution 2:[2]
This is my example using laravel as backend. The param success in transport is a callback for processResults method. Use data function to get the value from the input.
{
// [..]
ajax: {
url : 'yourUrl',
data: function (params) {
let query = {
term: params.term, // Get value form input
page: params.page || 1
}
return query;
},
transport: function(params, success, failure){
axios.get(this.url, { params : this.data } )
.then(function(data){
success(data);
})
.catch(function(error){
console.log(error);
});
},
processResults: function (response, params) {
// params.page = params.page || 1;
return {
results: response.data.data,
pagination: {
more: response.data.links.next ? true : false,
}
};
},
},
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Arturs Mednis |
Solution 2 | backtheweb |