Autocomplete form populated by a database? - php

I am currently working on a project in which I need to have an autocomplete form call its information from a db file. I have seen many tutorials on jquery autocomplete forms, but I do not know how to call a db file to populate the list.
I am working in PHP. Currently the code represents a simple drop down box that is calling on the db file for population.
<?php
global $wpdb;
$depts = $wpdb->get_results( "SELECT * FROM departments ORDER BY department_name ASC" );
echo '<select>';
foreach($depts as $row) {
echo '<option name="select_dept" value="'.$row->department_id.'">'.$row->department_name.'</option>';
}
echo '</select>';
?>
Any help would be awesome!

I recently have used this library for autocompletion - http://www.devbridge.com/projects/autocomplete/jquery/
So here is brief script based on yours:
<?php
$query = isset($_GET['query']) ? $_GET['query'] : FALSE;
if ($query) {
global $wpdb;
// escape values passed to db to avoid sql-injection
$depts = $wpdb->get_results( "SELECT * FROM departments WHERE department_name LIKE '".$query."%' ORDER BY department_name ASC" );
$suggestions = array();
$data = array();
foreach($depts as $row) {
$suggestions[] = $row->department_name;
$data[] = $row->department_id;
}
$response = array(
'query' => $query,
'suggestions' => $suggestions,
'data' => $data,
);
echo json_encode($response);
} else {
?>
<html>
<body>
<input type="text" name="" id="box" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://www.devbridge.com/projects/autocomplete/jquery/local/scripts/jquery.autocomplete.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#box').autocomplete({
serviceUrl:'/',
// callback function:
onSelect: function(value, data){ alert('You selected: ' + value + ', ' + data); },
});
});
</script>
</body>
<html>
<?}?>

Please follow this very well written tutorial
http://www.nodstrum.com/2007/09/19/autocompleter/

JQuery UI includes an autocomplete, although you still need to write a PHP script to return the information to be added to the control as its done via AJAX. If you know in PHP how to connect to a database, query it, and return a list of the results - then you will have no problems with this. JQuery makes AJAX extremely simple.
Depending on how complicated your field/data set is - and assuming its not millions upon millions of unindexed records, I would be content to autocomplete from a:
SELECT thing WHERE thing LIKE '".$query."%'
So if you were searching for, say, food... the query "CA" would pull out CArrot and CAbbage and CAuliflower. If you added a % to the beginning of the LIKE, you could get results that contained your query, as opposed to just beginning with it.
The page your user hits would contain the JQuery part which both sends the request and creates the autocomplete effect from the results, and a very simple, separate PHP script which the AJAX request hits would return the potential 'matches'.
Take a look at the Autocomplete demos on JQuery UI

Related

jQuery UI autocomplete showing html code

I am having a problem with autocomplete that is confusing me a little. I did a search first, I am not the only one having this problem. But everyone seems to use jQuery Autocomplete in their own way, so it didn't really help me.
Anyway, here is the problem. I am building a search function, that is supposed to show a list of users, retrieved from a mysql database. I got that to work. So when I start typing, it immediately shows a list of users. What I want to do next, is to make the results links, that redirect the user to a different page.
Here is findartist.php;
if(isset($_GET['term'])){
$artist = new User();
$return_arr = array();
$results = $artist->findUser($_GET['term']);
foreach($results as $result){
$link = "<a href='profile/index.php?st=" . $result['stagename'] . "'/>" . $result['stagename'] . "</a>";
$return_arr[] = $link;
}
echo json_encode($return_arr);
}
And here is the jQuery;
<script>
$(function() {
//autocomplete
$(".artist_input").autocomplete({
source: "/includes/findartist.php",
minLength: 1
});
});
</script>
The problem is that when I do this, it shows the html code.
So this is what it would look like;
<a href='profile/index.php?st=bob'/>bob</a>
Is there a way to fix this?
This isn't how autocomplete is set-up to work. It's set up to assume what you return is the text you want to display. It can't handle HTML in the way you're asking.
However, that doesn't mean all is lost...
Instead of having findartist return an array of <a> tags, just the artist names.
Then, you write another function, bound to the 'select' event of the autocomplete object that will navigate you to the page you want.
See the documentation for the event in question here: http://api.jqueryui.com/autocomplete/#event-select
For example, findartist.php may change to:
if(isset($_GET['term'])){
$artist = new User();
$return_arr = array();
$results = $artist->findUser($_GET['term']);
foreach($results as $result){
$return_arr[] = $result['stagename'];
}
echo json_encode($return_arr);
}
And your autocomplete may look something like:
<script>
$(function() {
//autocomplete
$(".artist_input").autocomplete({
source: "/includes/findartist.php",
minLength: 1,
onSelect: function (suggestion) {
// event fires when the user selects something from the list.
window.location.href = "profile/index.php?st=" + suggestion;
}
});
});
</script>
Forgive me any mis-matched brackets or syntax error - I'm coding without a workign dev environment. Hopefully it helps anyway.
Try it out, see where you get.
you can work on form submit, it is the best way to redirected to results page
$(document).ready(function(){
$(".artist_input").autocomplete({
source: "/includes/findartist.php",
minLength:1,
select: function( event, ui ) {
$("#name").val(ui.item.label);
$("#form").submit();
}
});
});

Autocomplete not working using dynamic html

Iam adding html for input tag dynamically through enterPerson() and then calling onkeyup=changeOnType(this) which on echoing $results in autoInvit.php should display autocomplete, but WHY does my autocomlete code does not work,infact data shows if I alert it. can any one please help me out ?
Thank you in advance :)
header files for jquery and autocomplete:
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="//code.jquery.com/jquery-1.8.3.js"></script>
<script src="//code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
autocomplete in "main.php" :
<script>
function changeOnType(x){
$.post(
"autoInvit.php",
{
vals: $(x).val()
},
function(data){
$("#"+x.id).autocomplete( {source:"autoInvit.php" } );
//alert(data);
}
);
}
</script>
here's the dynamic html's php code in "invities.php":
<?php
echo '<input class="e" type="email" id="email" onkeyup="changeOnType(this)" autocomplete="on" role="textbox" aria-autocomplete="list" aria-haspopup="true" />';
?>
Here's my php file "autoInvit.php" which echos the result:
<?php
include("includes/connection.php");
$value = strip_tags($_POST['vals']);
$req = "SELECT email as name "
."FROM members "
."WHERE email LIKE '".$value."%' ";
$query = mysql_query($req);
while($row = mysql_fetch_array($query))
{
$results[] = $row['name'];
}
echo json_encode($results);
?>
Please help
There's no need to make the post request. Edit: There's no need to call a separate function or attach a listener to the input, just register the autocomplete plugin. This will need to be called once the DOM is ready, so you will need to wrap it in a ready function. This should be all the javascript you need:
$(function() {
$("#"+x.id).autocomplete( {source:"autoInvit.php" } );
});
What the user has typed will be passed with the request as the parameter term
From the jQuery docs for autocomplete:
String: When a string is used, the Autocomplete plugin expects that
string to point to a URL resource that will return JSON data. It can
be on the same host or on a different one (must provide JSONP). The
Autocomplete plugin does not filter the results, instead a query
string is added with a term field, which the server-side script should
use for filtering the results. For example, if the source option is
set to "http://example.com" and the user types foo, a GET request
would be made to http://example.com?term=foo. The data itself can be
in the same format as the local data described above.
Also, you'll want to be careful when passing content from the user directly to the DB. You can open yourself to SQL injection.

PHP jQuery dynamically populated SELECT

Have been looking around for a solution to this and have found some help on stack overflow but in most cases the examples I have found are not using arrays formed from a database query. Here is some code for what I am trying to achieve...
$stores = mysql_query("SELECT * FROM Stores");
$staff = mysql_query("SELECT * FROM Staff");
I would like to create two elements, one for stores and another for staff but I want to filter the staff based on the store client side. So if the user selects "Sydney" from the first dropdown, they are presented with only staff that work at the Sydney store in the second dropdown. Then if the user chooses "London" from the first dropdown, the Sydney staff are replaced by the London staff and so on.
My server side scripting is done with PHP and I am able to create the two dropdowns with PHP. But I am stuck on the jQuery to remove the I don't want from the second dropdown.
I know this is possible, because I see it used all the time. I have seen lots of examples of how to manage this but none of the examples use data from the PHP array to insert the .
You need ajax.
When the user selects something in a dropdown, this fires an event that you can process. Inside of this process you take the value of the selection like jQuery('#id_dropdown').val(), and send this via ajax (I like using POST since you dont run into GET request size limits).
You process this on the server side with php, accessing to the database with the value selected and sent via ajax. When you have the right results for the second dropdown you can output it via echo.
Finally, when the response is returned to jQuery, you can insert all the options in the new dropdown.
JAVASCRIPT PART:
Bind event to the first dropdown
Get value of the option selected in the dropdown
Make ajax request
Here is some example code:
var parameters='value_selected='+value_dropdown;
jQuery.Post({
url: '/destiny_when_I_process',
data: parameters,
success: func_callback
});
//here you can imagine a pause, because PHP is processing the data you send by post
//....
//....
//this part is executed when php send the information
function func_callback(response_from_php){
jQuery('#second_dropdown').html(response_from_php);
}
PHP PART:
get value from POST
access database using this value
echo (send response). You send a chain of text (in HTML), really this is not very professional, but is OK for demonstration purposes. Professionals send JSON, since JSON is lighter-weight.
JAVASCRIPT PART (SECOND PART)
in the callback function, you receive the response data via the first parameter
Insert new data in the second dropdown (since the data is already HTML, you do not need to process it)
for the secondary drop down, yes, you'll need some ajax.
You can create a script that go fetch the result coresponding to the store and send back the option listm witch is inserted in the ooption.
Using jquery and php you'll need a few thing.
A php file to get the result and return the options. (let say getStaff.php)
<?php
//get the store id by post is it is set
if (isset($_POST['store->id']) $store_id = mysqli_real_escape_string($_POST['store_id']);
//get the data !! notice the WHERE caluse
$r = mysql_query("SELECT * FROM Staff" *WHERE store=''$store->is*);
//split the data in the array
$staffs=array();
while ($assoc = mysql_fetch_assoc($r)) {
//Varialbe = $assoc['colum_name'];
$staff->id=$assoc['id'];
$staff->name=$assoc['name'];
//and so on for each colum in your table.
array_push($staffs, $assoc);
}
//echo the result as option
foreach ($staffs as $staff) echo "<option value='$staff->id'>$staff->name</option>";
?>
In you first select, add
onchange="$.post('getStaff.php', {store_id:$(this).val()}, function (data){ $('#staff_select').html(data);});"
and add an id to your second select (staff_select) in this ecample.
As an explanation: When the 1st dropdown change, it send a request to getStaff.php with the store_id as a POST argument. The php sript get the syaff according to the store Id and bring back a list of option tags for your secondary select. Than jquery add the 'data' to your secondary select and VOilĂ !
Hope tih sis clear cause it's a bunch of little thing together that will make it work. Sorry if it's seems sloppy as an answer but it's really simple once you know it.
Spent the afternoon learning how to do this and it's working quite well. Posted the new code here for others....
Thanks to http://forum.codecall.net/topic/59341-php-sql-jquery-and-ajax-populate-select-boxes/ for the tutorial.
And thanks to everyone here.
PHP to build for the first :
function agency_select() {
include('../include/dbase.php');
$agencies = $pdo->query("SELECT * FROM agency WHERE Status='active' ORDER BY AgencyName");
$opt = '';
while ($age_array = $agencies->fetch(PDO::FETCH_ASSOC)) {
$opt .= '<option value="'.$age_array['AgencyId'].'">'.$age_array['AgencyId'].' - '.$age_array['AgencyName'].' - '.$age_array['AgencySuburb'].'</option>'."\n\t\t\t\t\t\t\t";
}
return $opt;
}
HTML for the two elements:
<label for="AgencyId">Client/Agency:</label>
<select class="uniform" id="AgencyId" name="AgencyId" style="width: 400px; overflow-x: hidden">
<?php echo agency_select(); ?>
</select>
<label for="Contact">Contact: </label>
<select class="uniform" id="Contact" name="Contact" style="width: 300px; overflow-x: hidden">
<option value="">----Select Client/Agency----</option>
</select>
AJAX file:
if(isset($_POST['AgencyId'])) {
include('../include/dbase.php');
$option = '<option value="">----Select Contact----</option>';
$query = $pdo->prepare("SELECT * FROM client WHERE AgencyId= ? AND Status='active' ORDER BY FirstName");
$result = $query->execute(array($_POST['AgencyId'])));
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$option .= '<option value="'.$row['id'].'">'.$row['FirstName'].' '.$row['LastName'].'</option>';
}
echo $option;
}
jQuery:
$(document).ready(function () {
update_contacts();
});
function update_contacts() {
$('#AgencyId').change(function() {
$('#Contact').fadeOut();
$('#loader').show();
$.post('../ajax/ajax_contact_select.php', {
AgencyId: $('#AgencyId').val()
}, function (response) {
setTimeout("finishajax('Contact', '"+escape(response)+"')", 400);
});
return false;
});
}
function finishajax(id,response) {
$('#loader').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
i'll try to help you as much as i can a explain it.
mysql_query, you sould use mysqli btw, mtsql being decrecated, return a result set.
This means you will have all the records from your query. You need to brak down your result into before you can work with it. This is done by using methids like mysql_fetch_assoc, mysql_fetch_row, etc. There something like fetch to array to but i don't master it so i will use fetch assoc, for this reply.
So once you have yoru result set, $stores & $staff in your case, you then call a while loop on your results to get th data as in:
while ($assoc = mysql_fetch_assoc($r)) {
//Varialbe = $assoc['colum_name'];
$stores->id=$assoc['id'];
$stores->name=$assoc['name'];
//and so on for each colum in your table.
array_push($stores, $assoc);
}
Then you can export it as you want.
in you case would be something like
foreach ($stores as $store) echo "<option value='$store->id'>$store->name</option>";
I storngly suggest you take alook at http://php.net/manual/en/function.mysql-fetch-array.php witch will do the same a fetch_assoc bu with an array with the columname as key.

jquery-ui-1.8.14 Autocomplete with php and mysql

I'm not very much into js and programing in general, but I'm very stuck on something that really shouldn't be too difficult. Feel free to visit the test page:
[REMOVED LINK]
I have three autocomplete fields: Current club, nation and career stats.
Autocomplete works perfectly for the career stats where I can also add fields and the autocomplete also works for the added field.
But for the current club and nation fields, I get results while typing but when I click the correct output it doesn't show up in the input-field.
I can make it work using other js-libraries, but then it no longer work for the add-button career stats fields.
I use the following libraries:
<script type="text/javascript" src="js/jquery-1.6.3.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.14.custom.min.js"></script>
<script type="text/javascript" src="js/jq-ac-script.js"></script>
The current club html looks like:
<p>
Current club <label>:</label>
<input type="text" id="currentclub" />
</p>
In the custom made jq-ac-script.js (I originally found this somewhere online - don't remember where) the important part is:
$(document).ready(function(){
$( "#currentclub" ).autocomplete({
source: "get_club_list.php",
minLength: 1
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( item.currentclub )
.appendTo( ul );
};
});
The "get_club_list.php" looks like:
<?php
include ("dbsetup.php");
$return_arr = array();
$param = $_GET["term"];
$fetch = mysql_query("SELECT * FROM FootNews_CLUB
WHERE clubShortName LIKE '%$param%'");
/* Retrieve and store in array the results of the query.*/
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['currentclub'] = $row['clubShortName'];
array_push( $return_arr, $row_array );
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
Any ideas whereas to why the selected club doesn't show up when I click it would be appriciated!!
Wow, used my php code. Cool, glad I could help.
http://www.jensbits.com/2010/03/29/jquery-ui-autocomplete-widget-with-php-and-mysql/
Not sure why you are using the autocomplete code with _renderItem in it. I don't think you need it.
Change the php code to this:
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['currentclub'] = $row['clubShortName'];
$row_array['value'] = $row['clubShortName'];
array_push( $return_arr, $row_array );
}
And, the jquery to:
$( "#currentclub" ).autocomplete({
source: "get_club_list.php",
minLength: 1
});
You can read through my tutorial again but the autocomplete needs a label or value field returned. It then populates the select list and the corresponding input field with that value.
I left in $row_array['currentclub'] = $row['clubShortName']; because I don't know if you are grabbing that later on. If you are not, you don't need that line either.
Since you control the returned data and can specify a label and/or value field in the php, I don't understand why you are using the _renderItem for any of the autocompletes.
BTW, you should add mysql_real_escape_string to your php code for some sql injection protection: http://www.php.net/manual/en/function.mysql-real-escape-string.php

Load Javascript array with MYSQL database data

suppose i have an javascript array "userName".I want to load it from a database table named "user".
Can anyone help with idea or sample code?
Thanks
You'll have to use the mysql_connect(), mysql_select_db() functions in PHP to connect to your db. After that use mysql_query() to SELECT the fields in your user table (if your user table has the fields name and id, SELECT name, id FROM user). Then you can fetch all infos from the db with mysql_fetch_assoc() or any other mysql fetch function. Now you need to echo your data into the javascript on your website, formatted as an array. This is complicated to get right, but you can get help from json_encode.
To fill your array with the user names, you'd do something like this.
<html>
<head>
<script type="text/javascript">
var userName = <?php
// Connect to MySQL
//mysql_connect();
//mysql_select_db();
$d = mysql_query( "SELECT name, id FROM user" ) or die( mysql_error() );
$usernames = array();
while( $r = mysql_fetch_assoc($d) ) {
$usernames[] = $r['name'];
}
echo json_encode( $usernames );
?>;
// Do something with the userName array here
</script>
</head>
Use ajax and php as an intermediate :
Define an empty JS array :
var myarray = new Array();
use ajax to call your php script, javascript will eval the output by PHP (note this uses prototype library):
new Ajax.Request('myfile.php', {
onSuccess : function(xmlHTTP) {
eval(mlHTTP.responseText);
}
});
Write your PHP code to grab data and print JS code (it must be valid javscript !) :
$i=0; $q=mysql_query('select ..');
while($row=mysql_fetch_array($q)){
echo "myarray[".$i."]='".$row['data']."';";
$i++;
}
You can check that your Js array contains data :
alert(myarray.length);
hope this helps.
This creates a global user variable in your page.
<?php
$user = /* get information from database the way you usually do */;
// $user == array('id' => 1, 'name' => 'foo', ...);
?>
<script type="text/javascript" charset="utf-8">
var user = <?php echo json_encode($user); ?>;
</script>
If you're looking for a dynamic AJAXy solution, follow some tutorials about AJAX.
The best way to do that simply is to get your data in your php code, and then "write" the javascript code to generate the array in php.
A short example would be :
echo "a = new Array();";
foreach($row in $results)
{
echo "a[$row[0]] = $row[1];";
}
My code could be quite incorrect, it's juste to give you a quick example.
You could also do that in a more elegant way, using json.

Categories