Streamline Ajax Jquery Autocomplete with json data

Asked

Viewed 409 times

4

I want to make suggestions dynamically with this API.

How to streamline the suggestion file by listing data from the mysql database?

Download the DEMO: https://github.com/devbridge/jQuery-Autocomplete

The archive countries.js is what contains the suggestions dictionary, but manually, I want something dynamic with the suggestions registered in the database being listed in it.

countries js.

    var countries = {
    "AD": "Andorra",
    "AE": "United Arab Emirates",
    "AF": "Afghanistan",
    "AG": "Antigua and Barbuda",
    "AI": "Anguilla",
    "AL": "Albania",
    "AM": "Armenia",
    "WK": "Wake Island",
    "WS": "Samoa",
    "YD": "People's Democratic Republic of Yemen",
    "YE": "Yemen",
    "YT": "Mayotte",
    "ZA": "South Africa",
    "ZM": "Zambia",
    "ZW": "Zimbabwe",
    "ZZ": "Unknown or Invalid Region"
}

Instructions from the API Manual

Response format The Server Response must be JSON formatted following Javascript object:

{
    // Query is not required as of version 1.2.5
    "query": "Unit",
    "suggestions": [
        { "value": "United Arab Emirates", "data": "AE" },
        { "value": "United Kingdom",       "data": "UK" },
        { "value": "United States",        "data": "US" }
    ]
}

Data can be any value or object. Data object is passed to formatResults function and onSelect callback. Alternatively, if there is no data you can only provide a string array for suggestions, such as:

{
    "query": "Unit",
    "suggestions": ["United Arab Emirates", "United Kingdom", "United States"]
}

1 answer

3

As in the example of the site that was mentioned, you should add a URL to the attribute serviceUrl in the component configuration object, something like .

This URL should point to a server-side page that returns a JSON in the desired format. You can set this by modifying the request headers. In PHP, you can still serialize the json object directly, as in the example below.

<?PHP
$data = /** Objeto a serializar **/;
header('Content-Type: application/json');
echo json_encode($data);

On this page you should use the format you already know to access the database and etc.

  • Hello @vkrausser good night and thanks for your attention, could you post an example so I can understand a little better? Tks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.