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
Related
I am using wordpress and I want to have a search textbox that would autocomplete upon keychange. The results for the autocomplete should come from the database that contains the product names.
Here's what I have but it's not working. Nothing shows up.
$(document).ready(function() {
$("#product").autocomplete({
source: function(request, response){
$.getJSON("../searchProduct.php"){
term: $(#product).val()
}, response);
}
});
on searchProduct.php, I have:
<?php
global $wpdb;
require_once('/wp-config.php');
$searchTerm = $_GET['term'];
$searchTerm = esc_sql($searchTerm);
$searchTerm = like_escape($searchTerm);
$results = $wpdb->get_results("SELECT * FROM wp_products WHERE productName LIKE '".$searchTerm."%'");
foreach ( $results as $products ) {
$data[] = $products->productName;
}
}
echo json_encode($data);
?>
What could be the problem? Thank you in advance!
It is hard to tell what exactly the issue is without some error information. If you inspect, what is the response code? 404? 500?
One thing I notice is that you are using $(document).ready(function() {, and Wordpress requires no-conflict jQuery wrappers. Try switching that line out for jQuery(function($) {
Here is some more info if you need it: http://wptricks.net/jquery-noconflict-wrappers-on-wordpress/
<?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.
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();
}
});
});
I have googled and looked at SO for a while now and can't seem to figure this out. The only requirement Im trying to meet is to return a properly formatted javascript array that contains the results of the sql statement.
I.E.
Given a query:
SELECT NUMBERS FROM TABLE
And results:
NUMBERS
1
2
3
I would like to eventually get back an array like so
["1","2","3"]
Please help me understand where I am going wrong
Here is my php code
<?php
$mysqli = new mysqli("local.host.com", "user", "pass", "db");
$sql = "SELECT DISTINCT NAME FROM table";
$result = $mysqli->query($sql);
while($row = $result->fetch_array())
{
$rows[] = $row['NAME'];
}
echo(json_encode($rows));
$result->close();
/* close connection */
$mysqli->close();
?>
Here is my javascript:
function GetCards()
{
var cardarray = new Array();
//alert('test');
$.getJSON('getcardlist.php', function(data)
{
for(var i=0;i<data.length;i++)
{
cardarray.push(data[i]);
}
//return cardarray;
});
return cardarray;
}
EDIT:
Little more information, Im trying to setup an autocomplete list for jquery ui, this is my setup for the autocomplete widget.
var list = GetCards();
$( "#name" ).autocomplete({
source: list,
minLength: 2
And this is the error Im getting from chrome console
Uncaught TypeError: Cannot read property 'label' of null
GetCards is returning an empty array -- which is what you're passing on to the Autocomplete widget -- and causing the widget to throw up the TypeError exception. To pass on the populated array, move the code that instantiates Autocomplete into your getJSON success callback (I'm not sure you even need to loop through data -- unless you need to actually transform its contents in some way):
$.getJSON( 'getcardlist.php', function( data ) {
$( "#name" ).autocomplete( {
source: data,
minLength: 2
} );
} );
Alternatively, consider using Autocomplete's shorthand for loading directly from the data feed (see passing source as a string). However, this approach may require some additional work on the server-side to filter down the list as the user types -- if you want that behavior.
you have to use $.each to get the data
$.getJSON('getcardlist.php', function(data)
{
$.each(data, function(key, val) {
cardarray.push(val);
});
//return cardarray;
});
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