I have a javascript code that I am using for my autocomplete search feature and it is working fine. But if you look at the code below, the data that the search feature is returning is hard coded and I want to get the data from MySQL using PHP.
Anyone can help me how to convert the code below to use PHP query to gather data MySQL then use the results and pass it to javascript? Thank you.
//<![CDATA[
var a1;
var a2;
function InitMonths() {
a2.setOptions({ lookup: 'January,February,March,April,May,June,July,August,September,October,November,December'.split(',') });
}
function InitWeekdays() {
a2.setOptions({ lookup: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(',') });
}
jQuery(function () {
a1 = $('#query').autocomplete({
width: 448,
delimiter: /(,|;)\s*/,
lookup: 'Andorra,Azerbaijan,Bahamas,Bahrain,Bangladesh,Barbados,Belarus,Belgium,Belize,Benin,Bhutan,Bolivia,Bosnia Herzegovina,Botswana,Brazil,Brunei,Bulgaria,Burkina,etc'.split(',')
});
a2 = $('#months').autocomplete({
width: 448,
delimiter: /(,|;)\s*/,
lookup: 'January,February,March,April,May,etc'.split(',')
});
$('#navigation a').each(function () {
$(this).click(function (e) {
var element = $(this).attr('href');
$('html').animate({ scrollTop: $(element).offset().top }, 300, null, function () { document.location = element; });
e.preventDefault();
});
});
});
New
Based on this auto complete plugin http://www.devbridge.com/projects/autocomplete/jquery/
Your JavasSript will need to look something like:
And your PHP (search.php) will need to be:
The plugin expects json like the below which this PHP should provide
Note I haven’t tested this but it should be fine!
Old Answer
See here: http://www.simonbattersby.com/blog/jquery-ui-autocomplete-with-a-remote-database-and-php/
First of all if you’re not using the jQuery autocomplete plugin (the one supported by jQuery as part of jQuery UI) set that up. http://jqueryui.com/demos/autocomplete/#remote
You’re asking how to completely rework the system.
For a start you’ll need to use Ajax to send the match string to the database via PHP as a proxy, then PHP will need to return the results and have the Javascript read them.
So you’ll need to use (as the config):
And something like (as your PHP)