'How to auto populate preferredCountries from intl-tel-input with db output
I would like to populate the preferredCountries:["xx","yy","zz"] with a function that fetches the most used country codes from a mysql db and list them highest first and at least with a count of 4
I have a site with bootstrap4 and datatables and want to populate the preferred list so you wont have to scroll to much.
var input = document.querySelector("#CountryPhone");
var iti = window.intlTelInput(input, {
initialCountry: "auto",
separateDialCode: "true",
autoPlaceholder: "aggressive",
utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-
input/14.0.7/js/utils.js",
preferredCountries:["gb","us","at"],
geoIpLookup: function(success, failure) {
$.get("https://ipinfo.io", function() {},
"jsonp").always(function(resp) {
var countryCode = (resp && resp.country) ? resp.country : "";
success(countryCode);
});
},
});
I have this sql in a function in a seperate php file:
"SELECT DISTINCT c.iso_code FROM countries c
LEFT JOIN customer cu on c.country_name = cu.country_name
GROUP BY c.country_name
HAVING count(cu.country_name) >= 4
ORDER BY count(cu.country_name) DESC, c.iso_code ASC"
and the return is a json_encoded output like the one that is needed: ["xx","yy","zz"]
I thought of doing something like:
preferredCountries: function() {
$.ajax({
url:"fetch.php",
method:"POST",
data:{action:"f2Countries"},
dataType:"json",
success:function(data){},
error: function() { }
});
},
But i am not strong in this so my guessing skills is up. The function under preferredCountries is never called. I have debug enabled and breakpoint inside the function it should go to but it never comes that far.
So need some help creating the right function, like the one for geoIpLookup that i borrowed from the documentation.
Solution 1:[1]
I finally solved my issue.
So basically I wanted to dynamically fill "preferedCountries" with the country codes of those countries that was used the most, and in descending order.
with an $.ajax() call I ask my database to fetch the country codes in desc order and returning the data in json format
I make sure to destroy the var iti and reinitiate it with the variable.
preferedCountries = JSON.parse(data)
iti.destroy();
iti = window.intlTelInput(input, {
separateDialCode: "true",
autoHideDialCode: "true",
autoPlaceholder: "polite",
preferredCountries: preferedCountries,
utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/14.0.7/js/utils.js",
customPlaceholder: function(selectedCountryPlaceholder, selectedCountryData) {
return "e.g. " + selectedCountryPlaceholder;
}
});
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 | Stgr |