Autocomplete using jquery in wordpress not working - php

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/

Related

My jQuery autocomplete is not working

Im trying to use jQuery autocomplete to show my title of news while Im writting on my search form.
But Im having a problem, when Im writing in my search input nothing appears.
I have my header.php file where I have this script to start jQuery autocomplete:
$(function(){
$('.j_autocomplete').autocomplete({
source: "search.php",
});
});
I also have in my header.php a menu with a search form:
<nav id="menu">
<ul>
<li>Home</li>
.....
<li>
<form id="search">
<input name="search" class="j_autocomplete" type="text" placeholder="Search..." />
<button type="submit">Search</button>
</form>
</li>
</ul>
And then I have my source, that is my search.php file, where Im selecting my news title to show on my jQuery autocomplete:
<?php
$search= $_GET['term'];
$readNews = $pdo->prepare("SELECT * from news WHERE title LIKE ? ORDER BY title ASC");
$readNews->bindValue(1, "%$search%", PDO::PARAM_STR);
$readNews->execute();
$resJson = '[';
$first = true;
while($res = $readNews->fetch(PDO::FETCH_ASSOC))
{
if(!$first)
{
$resJson .= ', ';
}
else
{
$first = false;
}
$resJson .= json_encode($res['title']);
}
$resJson .= ']';
echo $resJson;
?>
Everything looks fine for me, and If in my search.php file I put only this code below, I get all this 4 names when I start to writing in my autocomplete,
so it seems that my source is also correct:
<?php
$result = array("Henry","Tom","Terry","Chris");
echo json_encode($result);
?>
Do you see where might be my error?
In autocomplete documentation says that 'term' is querystring key to use, but
I suspect that is something about my $_GET['term'] that is not working correctly, but I already tested with $_REQUEST['term'] and also dont works!
EDIT:
After hours of debugging, and structure changes we finally got it to work.
The problem were a mix of .htaccess rewrites and some small bugs in the previous code.
I'm not sure how to describe everything we did to make it work.
--
Try building your json string more robust.
$data = array();
while($res = $readNews>fetch(PDO::FETCH_ASSOC))
{
$data[] = $res['title'];
}
echo json_encode($data);
EDIT:
To check for undefined index, typ
$search = isset($_GET['term']) ? $_GET['term'] : "";
I'm sympathetic to your plight - I was in the same mess about a year ago, and then I received some great help here on SO.
All of my errors with autocomplete were because I was not presenting a true json file to the autocomplete function. So I learned that for each and every PHP file that you write, run it as a stand-alone, grab the screen output, and test it with jsonlint.
The second thing I was taught is that it may be easier (if you don't have too many variables to read) if you call the entire file with your php first, then present it to the autocomplete function. Once I started with these two steps, I haven't had a major glitch since. Hope it helps you.
JS
$(function(){
$.ajax ({
url: "../php/insurancesinglevarjson.php",
dataType: "json"
})
.done(function (data) {
console.dir(data);
var source = data;
$("#companyname").autocomplete({
source: source});
});
});

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 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

How do I use php to feed data to jQuery autocomplete?

I'm trying to build a form where certain text fields and text areas have autocomplete.
I've used the formidable plugin for wordpress to build my form. I'm using the jQuery autocomplete plugin for the autocomplete part.
The code looks like this:
<script>
$(document).ready(function(){
var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");
$("#example").autocomplete(data);
});
</script>
So basically I need to use php to pull data from the mysql database and feed it to that data var. I'm a php newbie, so I'm not sure how to do this. A coder who works on the formidable plugin suggested the following code for the var data part:
<?php
global $frm_entry_meta;
$entries = $frm_entry_meta->get_entry_metas_for_field($field_id, $order='');
?> //db_frm_entry_metas is the name of the mysql db that stores the values for every field from the form. I suspect get_entry_metas_for_field is a function added by the formidable plugin. $field_id is the id for a given field on the form.
var data = new Array();
<?php foreach($entries as $value){ ?>
data[] = <?php echo $value ?>;
<?php } ?>
I tried to run this code with an id number in the place of $field_id, but it didn't work. I'm stuck here.
I can understand most of the code, except for this part:
var data = new Array();
<?php foreach($entries as $value){ ?>
data[] = <?php echo $value ?>
I don't get what the data[] is doing there... should the php be feeding the data to the var data= line?
I have around 15 form text/textarea fields, each of which needs to pull data associated with its given field_id. Unless there's an easier way to do this, this means I'll have to write 15 scripts, each with a particular $field_id and jQuery object with field's css selector.
Any help getting this to work would be much appreciated!
The coder is wrong, this:
data[] = something;
will cause a syntax-error in JS, it's a PHP-shorthand for pushing members to an array and doesn't work in JS.
Try this:
data.push(unescape('<?php echo rawurlencode($value); ?>');
According to the autocomplete docs, you can pass a url as the data parameter. That being said, do something such as the following:
<?php
// --- PLACE AT VERY TOP OF THE SAME FILE ---
$search = isset($_GET['q']) && !empty($_GET['q']) ? $_GET['q'] : null;
if (!is_null($search))
{
$matches = Array();
// some search that populates $matches based on what the value of $search is
echo implode("\r\n",$matches);
exit;
}
?>
then, in your jQuery code replace the .autocomplete(data) with .autocomplete('<?php echo $_SERVER['PHP_SELF']; ?>');
your jquery will be something like this
$("#example").change(function(){
$.ajax(
{
type: "POST",
url: "php_page.php",
data: "data=" + $("#example").val(),
beforeSend: function() {
// any message or alert you want to show before triggering php_page.php
},
success: function(response) {
eval(response);
// print your results
}
});
});
in your php page after getting all info echo the results like this.
echo "var result=" . json_encode($results);
then eval(response) jquery function will give you javascript variable result with your results in it.
Hope this helps...

Categories