jquery-ui-1.8.14 Autocomplete with php and mysql - php

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

Related

Loading mysql rows from PHP into autocomplete jquery

<?php
$cuvant = (isset($_GET['cuvant']) ? $_GET['cuvant'] : '');
// the word I want to get from the search box
$sql = "SELECT cuvant FROM cautare where cuvant like'".$cuvant."%'ORDER BY nr_cautari DESC limit 0,6";
// I search for that word in a table from database
?>
<script>
$(function() {
var cuvinte=['<?php
$resursa = mysql_query($sql);
?>'];
$( "#cautare" ).autocomplete({
// #cautare is the id of the search box
source: cuvinte
});
});
</script>
I'm trying to make an auto-completer with jQuery, and I have this code in the index.php page. I don't know how to fix this issue: When I try to search something on the page, nothing happens.
Assuming that you are using jQuery Autocomplete: https://jqueryui.com/autocomplete/
I believe the variable that contains the values has to be valid JSON. Even doing an mysql_fetch_assoc() is going to return a php array that looks something like this for each row:
array(
'cuvinte' => "something"
);
So, assuming that there are multiple rows returned from your query, I think you would need to do something like this:
<script>
$(function() {
var cuvinte=
<?php
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$resursa[] = $row['cuvant'];
}
echo json_encode($resursa);
?>;
$( "#cautare" ).autocomplete({// #cautare is the id of the search box
source: cuvinte
});
});
</script>
Basically, this takes the result of your query, loops through all the rows, and builds a temporary array. The last step is to take that array and let PHP turn it into json for you.

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();
}
});
});

Populating a Drop Down Menu (select)

I've been trying to solve my question based off of this answer:
Populate select box from database using jQuery
I've attempted to implement what is said in the answers there but I am not having any luck here. As of now all that appears in the drop down menu is the default "Stone" item that starts in it.
Could anyone spare some time and give me a hand fixing my issue. My code should essentially read from a MySQL database which has over 150 ID's in order starting at 1 and use the corresponding name in the same ID's row to populate the drop down menu on load.
Example of what drop down menu would look like inside of it:
Stone
Grass
Diamond
What corresponding DB would look like:
ID item_name
1 Stone
2 Grass
3 Diamond
The code I'm using to try and do this is:
PHP (process_item_list.php):
$con = mysql_connect($DB_HOST,$DB_USER,$DB_PASSWORD);
$dbs = mysql_select_db($DB_NAME, $con);
$tableName = "itemlist";
$result = mysql_query("SELECT * FROM $tableName");
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
?>
jQuery/Javascript
<script type="text/javascript">
$(function(){
var items="";
$.getJSON("process_item_lists.php",function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.name+"</option>";
});
$("#tradeItems").html(items);
});
});
</script>
HTML
<select id="tradeItems">
<option value="">Stone</option>
</select>
I'm open to different ways to do this as well, as long as it still fills the drop down menu on load!
Edit: With the help of wirey the PHP issue is fixed. Here is what the results look like from running the PHP file: http://fogest.net16.net/mctrade/php/process_item_list.php
When I run the actual page using the alert boxes which should give me the ID and the item name they both return undefined rather then the correct values.
The results at http://fogest.net16.net/mctrade/php/process_item_list.php doesn't look like what you're expecting, it looks like this:
[ ["1","Stone","images\/stone.png"],
["2","Grass Block","images\/grass_block.png"],
/* snip a lot of rows */
]
But what you are expecting is something like this:
[ { "id":"1", "name":"Stone", "image?":"images\/stone.png"},
{ "id":"2", "name":"Grass Block","image?":"images\/grass_block.png"},
/* and so on */
]
I think that you'll want to use mysql_fetch_assoc() instead of mysql_fetch_row(), that might give you proper output.
Bonus: you can give the response a proper content-type by adding a row before the echo:
header("Content-type: application/json");
echo json_encode($data);
Remark: when I inspected the source of http://fogest.net16.net/mctrade/php/process_item_list.php I found this at the end:
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
This should not be part of the response, it will probably make the JSON parser crash.

Autocomplete form populated by a database?

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

jQuery Autocomplete Mysql PHP

Hi could some one please take a look at this and let me know where I'm going wrong. I am trying to get jQuery UI autocomplete to work. this is my code:
This is search.php
include "db_connect.php";
$search = $_GET['term'];
$result = mysql_query("SELECT Title FROM `movie` WHERE `Title` LIKE '%$search%' ORDER BY Title ASC") or die('Something went wrong');
$rows = array();
while ($row = mysql_fetch_assoc($result)){
$rows[] = $row;
}
print json_encode($rows);
?>
this is my javascript inline script
<script type="text/javascript">
$(document).ready(function()
{
$('#auto').autocomplete(
{
source: "./search.php",
minLength: 3
});
});
</script>
and this is the 'auto' div
<div id="searchTxtFieldDiv">
<p><input type="text" id="auto" /></p>
</div>
When I look at the call using firebug I see that search.php is returning
[{"Title":"Sin City"}]
jQuery is just displaying UNDEFINED
any ideas??
Have a look at jquery ui autocomplete documentation. The JSON you are returning does not match what the autocomplete is looking for. The object you return must have properties named label or value (or both).
You can try the following options:
Option 1: Change returned JSON
Change the JSON being returned to include the label/value properties such as:
[{"label":"Sin City"}]
From the examples it also seems to use the id property. I believe the above is the minimum requirement for the autocomplete to display a list of values. I think you can also return an array of strings and it will render it in exactly the same way as the above.
[ "Sin City", "Etc" ]
Option 2 : Change private _render function
Change the private _renderItem function for the autocomplete to use your custom properties as shown in this autocomplete example (untested):
$( "#project" ).autocomplete({
source: "./search.php",
minLength: 3
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( item.Title )
.appendTo( ul );
};
This is a bit more flexible but much uglier imho.
#Shaun
Thanks mate, sometimes you just need someone to point out the obvious.
The way I finally got it to work was
include "db_connect.php";
$search = protect($_GET['term']);
$result = mysql_query("SELECT Title FROM `movie` WHERE `Title` LIKE '%$search%' ORDER BY Title ASC") or die('Something went wrong');
$json = '[';
$first = true;
while ($row = mysql_fetch_assoc($result))
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['Title'].'"}';
}
$json .= ']';
echo $json;
atleast run mysql_real_escape_string() on $search before jamming it into a SQL Query.
The source: bit in your javascript is probably messing it up. You should remove the . if 'search.php' is at the 'top' of the documentroot directory.
Firebug will probably help you take a peak at the communication as well.
I was going to say this, always sanitize user inputs.
It's hard to say since I never used jQuery autocomplete but I think you should target the value of "#auto". Something like this: $('#auto').val().autocomplet

Categories