remote request with php jQuery-autocomplete

Asked

Viewed 73 times

1

I’m trying to requisition remote file PHP with the plugin jQuery-autocomplete, but it’s not working. The plugin in question and this one: jQuery-autocomplete. I want to use it because it is very simple, light and meets what I need.

The requisition is made like this:

$('input[name="q"]').autoComplete({
minChars: 2,
source: function(term, suggest){
    term = term.toLowerCase();
    var choices = ['ActionScript', 'AppleScript', 'Asp', ...];
    var matches = [];
    for (i=0; i<choices.length; i++)
        if (~choices[i].toLowerCase().indexOf(term)) matches.push(choices[i]);
    suggest(matches);
}
});

In the var choices I need to put the file PHP that will return the result. The problem is not working. I have already looked at the documentation and there is no complete example. Can someone help me with that?

  • remote request would be what? a remote address? or the search file is local?

1 answer

1


The jQuery-autocomplete, has a basic request template that can be done so:

Html

<input type="text" name="q" />

Javascript

$('input[name="aj"]').autoComplete({
    source: function(term, response){
        $.getJSON('busca.php', { q: term }, 
                     function(data){ response(data); });
    }
});

Observing: where is busca.php change to the address of the file that will generate the data


Busca.php

The file must return a Json of a array simple of your code in PHP, example:

['aaa','aaaa','aaaaa']; // ou array('aaa','aaaa','aaaaa');

the example code as has no references in your question would be:

<?php

    $array['aaa'] = ['aaa','aaaa','aaaaa'];
    $array['bbb'] = ['bbb','bbbb','bbbbb'];
    $result = isset($_GET['q']) ? $array[$_GET['q']] : [];

    return json_encode($result);

The code works like this, by typing three aaa he takes the values ['aaa','aaaa','aaaaa'] and shows in the box the 3 items and so is also with the bbb. If you want to search the bank should adapt this idea.

Reference: autocomplete - An extremely lightweight Completion suggester plugin for jQuery.

  • very good, tomorrow sedo I will test, and if it works I mark the answer ok. I will try to adapt query in mysql BD. Tomorrow put here if it worked. Thank you very much.

  • @Hugoborges Ok, the code is functional ... can be used as a test and then go for adaptation ...

  • 1

    i tested the code here and it worked, but had to change the following line 'echo json_encode($result);'. Mia once, thank you very much.

Browser other questions tagged

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