php – List of countries and cities API

Question:

Good day to all, the other day I asked myself a question about the auto pulling of information from the API or from someone else's base for Cities and Countries.

Found a rather interesting chosen-js for creating a "live search" https://harvesthq.github.io/chosen/ . I got this form ( I work with Laravel 5.4 ):

<div class="form-group">
    <label class="control-label" for="title">City:</label><br>
    <select data-placeholder="Choose a city..." id="city" name="city" class="chosen-select-city">
        <option value="&nbsp;">&nbsp;</option>
        <option value="United States">United States</option>
        <option value="United Kingdom">United Kingdom</option>
        <option value="Afghanistan">Afghanistan</option>
        <option value="Aland Islands">Aland Islands</option>
        <option value="Albania">Albania</option>
    </select>
    <div class="help-block with-errors"></div>
</div>

<script>
jQuery(".chosen-select-city").chosen({no_results_text: "Oops, no city!"});
</script>

But I don’t know how to throw connections to the database or API, I can’t find at least an example. Since I perfectly understand that a database with 100,000+ cities will simply weigh more than one 100 mb, and it also needs to be updated, maybe there are any connections to google or is there something else?

And yes, I immediately warn you such an option as VK, Mail, Yandex, etc. do not offer as the project will operate on the territory of Ukraine

Answer:

A simple script can be written using jQuery. It will be possible to add a simple cache in the future, checking whether there has been a similar request before and retrieving the result from the cache. Below is a simple implementation (of course, you will need to add different checks for the field length and its content, for example).

html:

    <form action="/server.php">
        <input type="text" name="s" class="js_input">
        <select name="country" class="js_select">
            <option>Не выбрано</option>
        </select>
    </form>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <script src="ajax.js"></script>

js:

// сработает при вводе в input
$(document).on('keydown', '.js_input', function() {

    // если кол-во введенных символов меньше 3 ничего не делать
    if ($(this).val().length < 3) {
        return;
    }

    return getOptions();
});

// получить список стран
var getOptions = function() {

    var str = $('.js_input').val();

    $.ajax({
        url: "/server.php?s=" + str,
        type: "GET",
        success: function(res) {
            var array = JSON.parse(res);
            return renderOptions(array);
        },
        error: function(err) {
            console.log(err);
        }
    });
};

// добавить options в select
var renderOptions = function(array) {

    var options = '<option>Не выбрано</option>';

    if (array.length) {
        for (var i = 0; i < array.length; i++) {
            options += '<option value="' + array[i] + '">' + array[i] + '</option>'
        }
    }

    $('.js_select').empty().html(options);
};

php:

if(isset($_GET['s']) && !empty($_GET['s'])) {

    // ваша БД/API
    $countries = array(
        'Russia',
        'United Kingdom',
        'Germany',
    );

    $query = [];

    // Поиск в БД/API
    foreach($countries as $country) {
        preg_match_all("/(?<match>" . strtolower($_GET['s']) . ")" . "/", strtolower($country), $match, PREG_PATTERN_ORDER);
        if(count($match['match'])) {
            $query[] = $country;
        }
    }

    echo json_encode($query);
    die();
}
Scroll to Top