php / jquery autocomplete from mysql table - php

After referencing many previous questions and answers on this topic, I am still stumped. I am attempting to reference the database that stores a user's contact list. As an initial start, I'm keeping things simple and only allowing reference by email (rather than email, first and last names, etc).
I have the following linked:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$( ".emaillist" ).autocomplete({
source: "contacts.php"}); });
</script>
contacts.php: [UPDATED]
<?php
session_start();
include "scripts/sqlconnect.php";
$id = $_SESSION['id'];
$csql = mysql_query("SELECT * FROM db WHERE id='$id' AND email LIKE '%".mysql_real_escape_string($_GET['term'])."%'");
$contactlist = array();
while($row = mysql_fetch_assoc($csql)){
$contactlist[] = $row['email'];
}
$contactlist = json_encode($contactlist);
header('Content-Type: application/json');
echo "$contactlist";
?>
And finally the relevant HTML snippet:
<input name="semail" type="text" class="emaillist" id="semail"/>
Any suggestions on what I've done wrong? I can't seem to pinpoint the issue.

2 things that I notice:
You never output the contents of $contactlist
You aren't setting the appropriate Content-Type header.
So you want to do this:
$contactlist = json_encode($contactlist);
header('Content-Type: application/json');
echo $contactlist;
According to the documentation, the value passed to the AJAX source is called term, so you should be using that in your query, not semail:
... AND email LIKE "%'. mysql_real_escape_string($_GET['term']) .'%"');
^^^^-- Here

Related

jquery autocomplete sends empty get value to php

i am very new to jquery n javascript. I am trying to make an autocomplete feature. I am using a sample code from a diff page to do this. but the 'term' it passes to the php page is empty. so the autocomplete doesnt work. I dont understand why, can someone take a look? I didnt change the labels but i am just trying to test it to see if it works. the issue is with the php page, the request 'term' is empty.
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(function() {
$( "#txtLanguage" ).autocomplete({
source: "source.php",
minLength: 1 // how many character when typing to display auto complete
});
});
</script>
</head>
<body>
<label for="Language">Language: </label>
<input id="txtLanguage" class="txtLanguage"/>
</div>
</body>
</html>
<?php
include 'dbconnect.php';
$q=$_REQUEST['term'];
echo $q;
$return = array();
$stat="SELECT email FROM users WHERE email LIKE '$q'";
$query = sqlsrv_query($conn,$stat);
while ($row = sqlsrv_fetch_array($query,SQLSRV_FETCH_ASSOC)) {
array_push($return,array('label'=>$row['email'],'value'=>$row['email']));
}
echo(json_encode($return));
?>
I think you need this:
$stat="SELECT `email` FROM `users` WHERE `email` LIKE '$q%'";
You forgot for % symbol and LIKE without % is equal to email = '$q'
Are you sure, the file path is correct? Is there any javascript error in the console?
Try console $( "#txtLanguage" ).
Remove source.php and add an array
Hope this helps you.
Use $_GET['term'] instead of $_REQUEST['term']

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.

Passing variable to PHP from JS [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I know its REALLY simple, but I'm a newbie. I want to pass a variable from a PHP query via JS (for open-flash-chart) to the data file which is PHP.
This is my JS inside my PHP file. I'm pretty certian my issue is with the JS part since I've never used it before.
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript">
var player = "<? echo $player1 ?>";
swfobject.embedSWF(
"open-flash-chart.swf", "my_chart", "900", "350", "9.0.0", "expressInstall.swf", {"data-file":"data2.php"} );
</script>
I am trying to pass the $player variable to the graph data file which is this ( data2.php)
<?php
include("include/session.php");
include 'open-flash-chart/php-ofc-library/open-flash-chart.php';
if (isset($_GET['player'])) {
$player = $_GET['player']; }
$sql = "SELECT pos FROM nflscore where username = '$player'";
Assuming you want to use the var player change this in your swfobject.embedSWF call
{"data-file":"data2.php?player=" + player }
data2.php?variable="whatever variable"
on the php side do
$variable=$_GET["variable"];
now variable is the variable that you passed and you can do what you want with it
Well it pretty much depends on your needs!
Will javascript alter that variable? if not, the best way to transfer data between php pages are sessions! there are other options such as cookies, get vars, post vars etc. but users may change them putting your script in an uncomfortable position of dealing with wrong information if users do!
Using sessions your first page would simply look like this:
<?php session_start(); $_SESSION['player'] = $player; ?>
<!-- [...] -->
<script type="text/javascript">
swfobject.embedSWF("open-flash-chart.swf", "my_chart", "900", "350", "9.0.0", "expressInstall.swf", {"data-file":"data.php"} );
</script>
<!-- [...] -->
session_start has to be put at the very beginning of your php file, no headers should be sent before that function!
Well, your data file would then just become something like this:
<?php session_start();
/* ...your includes and the rest... */
$sql = "SELECT pos FROM nflscore where username = '{$_SESSION['player']}'";
Using cookies instead is quite the same, you just don't have to start the session at the beginning of your script (but if its a game you should rely on them already)! whats best though, you can access the cookie afterwards in your javascript as well!
so that's what your first page should look like :
<?php setcookie('player', $player) // somewhere in the script ?>
<!-- [...] -->
<script type="text/javascript">
swfobject.embedSWF("open-flash-chart.swf", "my_chart", "900", "350", "9.0.0", "expressInstall.swf", {"data-file":"data.php"} );
</script>
<!-- [...] -->
an your data page also becomes :
$sql = "SELECT pos FROM nflscore where username = '{$_COOKIE['player']}'";
The third easy option is to just drop the information where it should be right from the beginning ;) so no sessions, no cookies but just plain get variables!
first file :
<!-- [...] -->
<script type="text/javascript">
swfobject.embedSWF("open-flash-chart.swf", "my_chart", "900", "350", "9.0.0", "expressInstall.swf",
{"data-file":"data.php?player=<?php echo $player ?>"} );
</script>
<!-- [...] -->
second file :
$sql = "SELECT pos FROM nflscore where username = '{$_GET['player']}'";
Things become different though if your javascript needs to change the variable's content

multi tags using auto suggest jQuery plugins

I use Auto suggest jQuery plugins from this site:
http://code.drewwilson.com/entry/autosuggest-jquery-plugin
for making tags multiple as like giving in that site.
But my problem is...
While selecting from the autosuggest, it was displayed in my input box but I don't want to display selected autosuggest again as like in example given in the link....but I am unable to do such things...
please help me...
code used by me as follows:
<link rel="stylesheet" type="text/css" href="view/stylesheet/autoSuggest.css">
<script type="text/javascript" src="view/javascript/jquery/jquery.autoSuggest.js"></script>
<script type="text/javascript"><!--
$("#product_tag1").autoSuggest("http://test.com/ajax", {minChars: 2, matchCase: true,selectedItemProp: "tag", searchObjProps: "tag"});
//--></script>
Ajax file like
<?
$input = $_GET["q"];
$data = array();
$query = mysql_query("SELECT * FROM my_table WHERE my_field LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['tag_id'] = $row['id'];
$json['tag'] = $row['tag'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>
May I suggest the Select 2 plugin as an alternative? It is in active development and has IMHO nicer features; for example showing the list of available tags when the control has focus and not allowing the same tag to be selected more than once.
It sounds like it will do exactly what you want, but please see the Tagging Example for a description of all of the options. I do not think it will be difficult to switch plugins, based on your example code.
By using following codes in document ready function of javascript
$(document).ready(function()
{
var data=null;
var data=;
$("#tag").autoSuggest("config->item('admin_folder').'/products/autosuggest');?>",{minChars: 2, matchCase: true,selectedItemProp: "name", searchObjProps: "name",selectedValuesProp:"value",preFill: data});
});

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

Categories