I would like to create an input element where if users enter the first letter, the user should be able to see the suggestions. If for example, users enter "A", all the country names that start with "A" should be suggested. Instead of making the calls to backend each time, I would like to download the entire JSON and wouls like to consume from there. Please advise the steps either in jquery or javascript. Thanks a lot.
Asked
Active
Viewed 72 times
-1
-
Do you have any code that you can share?Have you attempted to do it on your own? – Dan Philip Bejoy Mar 18 '17 at 19:52
-
Possible duplicate of [jQuery autocomplete with callback ajax json](http://stackoverflow.com/questions/9656523/jquery-autocomplete-with-callback-ajax-json) – Michael Mar 18 '17 at 19:55
1 Answers
0
I have modified my code to read the coutries array from the external source which could be your backend file.
<?php
// this is your ajax.php backend file
$countries = array("Austria","Belgium","Canada","Danmark");
echo json_encode($countries);
?>
$.ajax({url: "ajax.php", success: function(result){
/* read external file and parse data into json array*/
var availableTags = JSON.parse(result);
$( "#countries" ).autocomplete({ source: availableTags } );
}});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<label for="countries">Country: </label>
<input id="countries" />

Daniel F
- 73
- 1
- 7
-
Thank you very much for the response, Now I am clear how to autocomplete works. Can you please give some example, when the JSON is coming from the backend and it will be completely loaded, when user made the first request and user can consume from the same JSON instead of making the calls to backend each time – Sai c Mar 18 '17 at 20:37
-