Abhishek Salian
Abhishek Salian

Reputation: 934

Php Ajax Json search and fill the input field

I need to perform a search and save it in input field dynamically. I am new to Ajax.

This is what I have done. Did a query from database and encoded using json as below

[{"id":"1","name":"Jack"},{"id":"2","name":"Ace"},{"id":"3","name":"Test"}]

Now there is a form with an input field for name (note: only existing names from database allowed). When name is being entered, I need to perform a search within Json and get name and display below the input field (exactly how google search shows related search terms) and this name should be clickable once clicked it should populate the input text with that name. And also change value of an hidden input field with respective id.

<input id="name" type="text" name="name">
<input id="id" type="hidden" name="id">

As I said before only names within the list is allowed, if a non existing name entered hidden element shouldnt have a value or 0 in it.

How can I get it done? And it should be optimised (fast) as it will have to search among a huge data say about 15k-20k names.

Upvotes: 0

Views: 1869

Answers (1)

Ujwal Abhishek
Ujwal Abhishek

Reputation: 338

check this fiddle i created for your requirement, i used auto complete method

http://jsfiddle.net/X85LT/

var src = [{
"label": "Jack",
    "value": "1"
}, {
    "label": "back",
        "value": "2"
}, {
    "label": "tera",
        "value": "3"
}, {
    "label": "judo",
        "value": "4"
}];

$('.name').change(function() {
 $('.value').val(0);
});

$(".name").autocomplete({
    source: src,
    select: function (event, ui) {
        event.preventDefault();
        this.value = ui.item.label;
        $('.value').val(ui.item.value);
    }
});

// html

<input type="text" class="name" />
<input type="text" class="value" />

Upvotes: 2

Related Questions