Topic: Autocomplete with ajax request
Extarys pro asked 7 years ago
softcon premium answered 3 years ago
For anybody looking for an answer, it is possible to use Ajax to update the values of an autocomplete object in MDB. In the example below my Ajax response has filtered the result already, so javascript no longer handles that part (but you can add it in if required). The Ajax response returns a simple array of items based on the search text that was fed in. Also note, this is vanilla Javascript, no Jquery required:
var xhr = new XMLHttpRequest();
var isAjaxWaiting = false;
var dataList = []; //This will hold our updated data
//this function creates a delay
const wait = ms=>new Promise(resolve => setTimeout(resolve, ms));
//Init the search
function initSearch(){
const obj = document.querySelector('#search-autocomplete');
new mdb.Autocomplete(obj , {
filter: getUpdatedData
});
}
//send search text to ajax and keep looping until we have a response
const getUpdatedData = async (txt)=>{
if(txt!="" && !isAjaxWaiting){
sendDataToAjax(txt);
do{
await wait(300); //this forces a pause for 0.3 seconds - will loop if ajax hasnt returned yet
} while(isAjaxWaiting)
return dataList; //Once do/while loop is broken out, return global dataList
}else{
return [];
}
}
function sendDataToAjax(txt){
isAjaxWaiting = true;
xhr.open("POST", "/ajaxurlhere", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify([
"searchtext" : txt
]));
}
//Update global dataList when Ajax is returned
xhr.onreadystatechange = function () {
if (xhr.readyState === 4){ //4 = DONE
dataList = JSON.parse(xhr.responseText);
isAjaxWaiting = false; // Our do/while loop will be able to break now
}
};
Marcin Luczak staff commented 3 years ago
Hi @softcon,
Thank you for this information, it will surely help our community :)
Regards, Marcin
Rafał Rogulski free answered 7 years ago
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Answered
- ForumUser: Pro
- Premium support: No
- Technology: MDB jQuery
- MDB Version: -
- Device: -
- Browser: -
- OS: -
- Provided sample code: No
- Provided link: No