View on GitHub

Tutorial Part Five

Setting initial values and remote functions.

Initialize with values

A common scenario is to have some default or initial value set for the combo box. This is done by using the value property. This property can either be set directly in the original input tag, or it can be set within our js/script.js file during initialization. As the combo is currently set to recognize country codes as IDs, we set those in our index.php file:

index.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>MagicSuggest Tutorial</title>
    <link href="lib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="lib/magicsuggest/magicsuggest.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="css/style.css">
  </head>
  <body>
    <div class="container">
        <h1>Hello, world!</h1>
        <form action="subscribe.php" method="post">
            <div class="form-group">
                <label>First name</label>
                <input class="form-control" name="firstname"/>
            </div>
            <div class="form-group">
                <label>Last name</label>
                <input class="form-control" name="lastname"/>
            </div>
            <div class="form-group">
                <label>Countries</label>
                <input id="ms" class="form-control" name="countries[]" value="[3,5,6,7,39]"/>
            </div>
            <input type="submit" class="btn btn-success pull-right" value="Submit"/>
        </form>
    </div>


    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="lib/jquery/jquery-1.11.1.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="lib/bootstrap/js/bootstrap.min.js"></script>
    <script src="lib/magicsuggest/magicsuggest.js"></script>
    <script src="js/script.js"></script>
  </body>
</html>

Something interesting to note here is that when we are using an AJAX source to fetch the combo's results, the component is required to make a request to retrieve the records we ask it for initialization. This is only done when an inital value is set.

js/script.js

We make a small change to make it look nicer and display selections as a comma separated value string. Also, we are now performing our sorting server-side in which we only want to look through country names.

$(function() {

    var ms = $('#ms').magicSuggest({
        data: 'get_countries.php',
        valueField: 'idCountry',
        displayField: 'countryName',
        groupBy: 'continentName',
        mode: 'remote',
        renderer: function(data){
            return '<div class="country">' +
                    '<img src="img/flags/' + data.countryCode.toLowerCase() + '.png" />' +
                    '<div class="name">' + data.countryName + '</div>' +
                    '<div style="clear:both;"></div>' +
                    '<div class="prop">' +
                        '<div class="lbl">Population : </div>' +
                        '<div class="val">' + data.population + '</div>' +
                    '</div>' +
                    '<div class="prop">' +
                        '<div class="lbl">Capital : </div>' +
                        '<div class="val">' + data.capital + '</div>' +
                    '</div>' +
                    '<div style="clear:both;"></div>' +
                '</div>';
        },
        resultAsString: true,
        selectionRenderer: function(data){
            return '<img src="img/flags/' + data.countryCode.toLowerCase() + '.png" />' +
                    '<div class="name">' + data.countryName + '</div>';
        }
    });


});

get_countries.php

Every time the user types, a query parameter is sent to the server. The frequency of those sent messages is set with the typeDelay parameter. Also method is default to POST but that can be changed as well. See how we use the parameter to build our custom query and get exactly what we want. Now if you type par it should only return Paraguy and not France who had Paris as Capital.

<?php
    $mysql = new mysqli('localhost','root','root','magicsuggest', 8889);
    $q = isset($_POST['query']) ? $mysql->real_escape_string($_POST['query']) : '';

    $result = $mysql->query("select * from countries where countryName like '%" . $q ."%'");
    $rows = array();
    while($row = $result->fetch_array(MYSQL_ASSOC)) {
        $rows[] = array_map("utf8_encode", $row);
    }
    echo json_encode($rows);
    $result->close();
    $mysql->close();

?>

Wrapping up...

View the results
Download the files for the tutorial

That's all folks!