php, Jquery autocomplete multiple values, remote! - php

am new to jquery! I'm using jquery ui autocomplete in my application where the auto complete values comes from database. Here are codes that am using but nothing happens
search.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("webforum", $conn);
$q = strtolower($_GET["term"]);
$query = mysql_query("select name from groups where name like %$q%");
while ($row = mysql_fetch_array($query)) {
echo json_encode($row);
}
?>
Here is test.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> jQuery UI Autocomplete - Multiple, remote </title>
<link rel="stylesheet" href="theme/jquery.ui.all.css">
<script type="text/javascript" src="jquery/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="jquery/ui/jquery.ui.core.js"></script>
<script type="text/javascript" src="jquery/ui/jquery.ui.widget.js"></script>
<script type="text/javascript" src="jquery/ui/jquery.ui.position.js"></script>
<script type="text/javascript" src="jquery/ui/jquery.ui.autocomplete.js"></script>
<style type="text/css">
.ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
</style>
<script type="text/javascript">
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#birds" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "http://localhost/webforum/search.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
</script>
</head>
<body>
<div class="demo">
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds" size="50" />
</div>
</div>
</body>
</html>
Can anyone help me with this?
Thanx in Advance!

How does your json looks like?
in order to work wit jquery-ui autocomplete you need to have at least label and value properties:
{
'label' : 'your_label',
'value' : 'your_value'
}
in your js code you are asking for value property which doesn't seem to bes set on your json produced by php.
here is a similar question: Having problems with jQuery UI Autocomplete
so php has to build the results in the right way:
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("webforum", $conn);
$q = strtolower($_GET["term"]);
$return = array();
$query = mysql_query("select name from groups where name like %$q%");
while ($row = mysql_fetch_array($query))
{
//since we have just 1 value from the db just use it as both value and label
array_push($return,array('label'=>$row['name'],'value'=>$row['name']));
}
echo(json_encode($return));
P.S. it is not that safe make queries with $_GET[] parameters.

Taken from jQuery autocomplete docs.
The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.
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 request parameter "term" gets added to that URL. The data itself can be in the same format as the local data described above.
Assuming the above; adjust your code to the following:
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("webforum", $conn);
$q = strtolower($_GET["term"]);
$query = mysql_query("select name from groups where name like %$q%");
$results = array();
while ($row = mysql_fetch_array($query)) {
array_push($results, $row);
}
echo json_encode($results);
?>

Related

Tooltip does not shows results

I am working on a project where there is a list of 5 'Modules'(Module1, Module2... so on). Its displayed in a html table. Each module has some chapters in it and so when modules are displayed in the table, I need to make a tooltip so that when user hovers over the module name a small tooltip shows all the chapter titles associated with it. Pretty much successful in implementing this but stuck at a point where console is displaying message as
'Empty string passed to getElementById().' and no chapters are being shown in tooltip and tooltip appears with "Please Wait..".
Here is my code for the same,
this is my jQuery and AJAX,
<link href='jquery-ui.css' rel='stylesheet' type='text/css'>
<script src='jquery-1.12.0.min.js' type='text/javascript'></script>
<script src='jquery-ui.js' type='text/javascript'></script>
<script>
$(document).ready(function() {
// initialize tooltip
$(".panel-body td").tooltip({
track: true,
open: function(event, ui) {
var id = this.id;
var split_id = id.split('_');
var module_id = split_id[1];
$.ajax({
url: 'fetch_details.php',
type: 'post',
data: {
module_id: module_id
},
success: function(response) {
// Setting content option
$("#" + id).tooltip('option', 'content', response);
}
});
}
});
$(".panel-body td").mouseout(function() {
// re-initializing tooltip
$(this).attr('title', 'Please wait...');
$(this).tooltip();
$('.ui-tooltip').hide();
});
});
</script>
And fetch_details.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo '';
mysql_select_db('dbname');
$moduleid = $_POST['module_id'];
$sql= mysql_query("SELECT title FROM table WHERE module_id='$moduleid'");
$html = '<div>';
$i = 1 ;
if( $sql === FALSE ) {
trigger_error('Query failed returning error: '. mysql_error(), E_USER_ERROR);
} else {
while($row = mysql_fetch_array($result)){
$title = $row['title'];
$html .= "<span class='head'>"<?php echo $title ; ?> " :</span><span>"" mins</span><br/>";
$i++;
}
}
$html .= '</div>';
echo $html;
?>
Till now I am unable to find out what's going wrong with this . Any help or advice will be highly appreciated.
The whole structure of the tool tip has to be something like this:
1) for example if you want to tooltip over a td , the td tag must have a title(the $('td#yourid').tooltip() shows the title of the td tag with id of #yourid). even if you don't want the title for your tooltip, you have to use it inside the your tag and later you can change it by an ajax return value. so:
<table>
<tr>
<td id = "tooltip-1" href = "#" title = "Nice tooltip" style="height:100px;width:100px;border:1px solid black;"><td>
</tr>
</table>
2) the tooltip structure must be like this if you want to tooltip over the td tag itself
<script>
$(function() {
$("#tooltip-1").tooltip({
open: function( event, ui ) {
var x = $(this); //this is for getting the tooltip-1 object to later use in ajax call
$.ajax({
type: 'post',
url: 'fetch_details.php',
data: {
'yourdata-name': 'yourdata'
},
success: function(html){
x.tooltip({
content: html
});
}
});
}
});
});
</script>
so you have to put the object that you want to tooltip on, in a variable like x and then use that x in ajax to point to the object so the tooltip will show the result of the ajax returning value
3) tooltip is new in jquery-ui and is somehow incompatible with bootstrap. so if you are using bootstrap try to use the bootstrap version of tooltip
4) there are alot of coding error within your code for example the syntax of $html .= "<span class='head'>"<?php echo $title ; ?> " :</span><span>"" mins</span><br/>"; is completely wrong. e.g. you can't use <?php ?> inside another <?php ?>.
My advice would be to first run my code and echo a simple string from fetch-details.php to ajax success function to see that this structure works and then you can manipulate your code based on this structure
since you gave little information about your code and the error given (by line) this was all i could do to help. i hope this information helps you with your program

Retrieve data from mysql table using ajax

I'm trying to show MySQL data using Ajax. Unfortunately, I am unable to find the correct way. I was trying to show MySQL data on a select box. When I click on "select category" option then all category will show as dropdown.
here is my HTML code.
<!DOCTYPE html>
<html>
<head>
<title>PHP MySQL Insert Tutorial</title>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
</head>
<body>
<select id='category'>
</select>
<script src='fetch.js'></script>
</body>
</html>
I have used this JS code to send request. Here is my JS code.
$('#category').onclick(function(){
$.getJSON(
'fetch.php',
function(result){
$('#category').empty();
$.each(result.result, function(){
$('#category').append('<option>'+this['category']+'</option>');
});
}
);
});
I have used this php code to complete ajax request and database connection. Here is my PHP code.
<?php
define('HOST','localhost');
define('USERNAME', 'root');
define('PASSWORD','');
define('DB','ajax');
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
$category = $_GET['category'];
$sql = "select category from ajaxx where category='$category'";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('category'=>$row[0]));
}
echo json_encode(array('result'=>$result));
enter code here
mysqli_close($con);
?>
When you make the AJAX request, it's to this URL:
fetch.php
But then in the server-side code, you try to get a query string value:
$category = $_GET['category'];
You can't get a query string value that you never provided. So when you build your SQL query (which is wide open to SQL injection by the way), there's nothing to get from the database.
If you want to use a query string value, you have to provide one:
$.getJSON(
'fetch.php?category=someValue',
function(result){
//...
}
);
What value you provide or where you get that value is up to you. (Perhaps from $('#category').val()?) But it has to exist before you can use it.
You may have confused two things: (a) initially fetching the HTML code to populate the options of your <select> control, and (b) Catching the selected option and using it to perform another DB query, returning new data.
Please review this modified (untested) code sample:
<!DOCTYPE html>
<html>
<head>
<title>PHP MySQL Insert Tutorial</title>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
</head>
<body>
<select id='category'>
</select>
<div id="resultDIV"></div>
<script src='fetch.js'></script>
</body>
</html>
javascript/jQuery:
//Run on document ready to populate the dropdown box
$(document).ready(function(){
$.getJSON(function(){
'fetch.php',
function(result){
$('#category').empty();
$.each(result.result, function(){
$('#category').append('<option>'+this['category']+'</option>');
});
}
});
$(document).on('click', '#category', function(){
//run on click to take dropdown value and perform lookup
myCat = $(this).val();
$.ajax({
type: 'post',
url: 'getcategory.php',
data: 'category=' +myCat,
success: function(d){
//if (d.length) alert(d);
$('#resultDIV').html(d);
}
});
});
}); //END document.ready
I have used this php code to complete ajax request and database connection. Here is my PHP code.
<?php
/*** getcategory.php ***/
define('HOST','localhost');
define('USERNAME', 'root');
define('PASSWORD','');
define('DB','ajax');
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
$category = $_GET['category'];
$sql = "select category from ajaxx where category='$category'";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('category'=>$row[0]));
}
echo json_encode(array('result'=>$result));
enter code here
mysqli_close($con);
?>
Here are some basic, simple AJAX examples to study (the three links at the bottom, but also note the information from the first link). Copy them to your server and make them work - play around with them:
AJAX request callback using jQuery
Your ajax code needs some changes :
<!DOCTYPE html>
<html>
<head>
<title>PHP MySQL Insert Tutorial</title>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type="text/javascript">
function myAjax ()
{ $.ajax( { type : 'POST',
data : { 'category' : $('#txt_cat').val() }, // SEND CATEGORY.
url : 'fetch.php',
success : function ( result )
{ $( '#category' ).empty();
var arr = JSON.parse( result );
var sel = document.getElementById("category");
for ( i = 0; i < arr.length; i++ )
{ var option = document.createElement( "option" );
option.text = arr[ i ];
sel.add( option );
}
},
error : function ( xhr )
{ alert( "error" );
}
}
);
}
</script>
</head>
<body>
Enter category <input type="text" id="txt_cat"/>
<button onclick="myAjax()">Click here to fill select</button>
<select id='category'>
<option> - empty - </option>
</select>
</body>
</html>
fetch.php
<?php
$category = $_POST[ "category" ]; // CATEGORY FROM HTML FILE.
// CONNECT TO DATABASE AND QUERY HERE.
$result = Array( "111","222","333","444" ); // SAMPLE DATA.
echo json_encode( $result );
?>

Return in previous value if the value not exist in textbox values from database

Okay, the main problem in here is I need to compare the value get from database through ajax. The values of textbox is from database depending on its option value.
I saw this script but I can't figure out how I can mix it to my autocomplete code. The source is the one of my big problem.
<script>
$(document).ready(function() {
$("#auto").autocomplete({
source: function(request, response) {
var results = $.ui.autocomplete.filter(src, request.term)
, el = this.element[0];
if (results.length) {
el.value = results[0];
el.setSelectionRange(request.term.length, el.value.length);
}
response(results);
},
change: function (event, ui) {
if (!ui.item) {
this.value = '';
}
}
});
});
</script>
I want to return the textbox empty if the current value is not on the list.
My page
<script>
function changeAutoComplete (val) {
$( "#tags" ).autocomplete({
source: 'autocomplete.php?selected='+val
});
}
</script>
</head>
<body>
Drop1
<?php
$mysqli = new mysqli("localhost", "root", "", "2015");
$combo = $mysqli->query("SELECT * FROM category GROUP BY cat_code ORDER BY id");
$option = '';
while($row = $combo->fetch_assoc())
{
$option .= '<option value = "'.$row['cat_code'].'">'.$row['category'].'</option>';
}
?>
<select id="main" name="main" onchange="changeAutoComplete(this.value)">
<option value="" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
<div class="demo-frame">
<label for="tags">Tags: </label>
<input id="tags" name="items">
You are trying to get it from server. then you have to use remote example of auto-complete.
For that you have to use anonymous function function( request, response ) for your source.
Here is auto-complete remote example on below link
http://jqueryui.com/autocomplete/#multiple-remote
Update your source attribute as follow according to your need
source: function( request, response ) {
$.getJSON( "search.php", {
term: extractLast( request.term )
}, response );
}

Auto complete not showing result jquery

I am trying to create an auto complete using jqueryui.I am echo ing a database result from the remote file search.php.It is showing the correct word in the response of fire bug but the suggetion list is not at all showing in my html page.
Can anybody please help me?
i'm using the code of multipile ,remote demo in the jqueryui.com
my php code
<?php include("connection.php");
$q=mysql_real_escape_string($_GET['term']);
$x="select fieldname from tablename where fieldname like '$q%'";
$query=mysql_query($x);
while($row=mysql_fetch_array($query)) { echo $row['fieldname']."\n"; } ?>
========================================================================
------------------------------------------------------------------------
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
}
</style>
<script>
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#birds" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "search.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds" size="50" />
</div>
If your remote file is placed on different domain you have to use JSONP.
JSON dosen't support cross-domain data transfer.
Read more about Same Origin policy

javascript code is not being executed

I am working on this project in which I am trying to get a returned value so I can autofill my input boxes according to what the client selects.
This code however is not executing and I do not know why. When I remove the src="jquery area" $(#dropdown).on is an undefined method; not to sure what to do.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
//$.post(url, [data], [callback], [callback type])
("#dropdown").on('change', function() {//when you select something from the dropdown function run and will switch the data
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
</script>
Here's my full code
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//$DBH->prepare('SELECT first FROM contacts');
}
catch(PDOException $e) {
echo "I'm sorry, I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
//get query
$FNresult=$DBH->query('SELECT first FROM contacts');
//set fetch mode
$FNresult->setFetchMode(PDO::FETCH_ASSOC);
$dropdown = "<select name='contacts' id='contacts' >";
while($row =$FNresult->fetch()) {
$dropdown .= "\r\n<option value='{$row['first']}'>{$row['first']}</option>";
// echo getLN();
}
$dropdown .= "\r\n</select>";
echo $dropdown;
//}
/*
// Get last name
function getLN(){
$query = "SELECT last FROM contacts";
$LNresult=mysql_query($query);
$last;
while($row = mysql_fetch_assoc($LNresult)) {
$last = "{$row['last']}";
}
echo $last;
}//end getLN
*/
$DBH = null;
?>
<!-- javascript on client-side -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
//$.post(url, [data], [callback], [callback type])
("#dropdown").on('change', function() {//when you select something from the dropdown function run and will switch the data
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
</script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
/*("#dropdown").on('connection', function (stream) {
console.log('Ah, we have our first user!');
});*/</script>
<form action="insert.php" method="post">
First Name: <input type="text" id="first" name="first"><br>
Last Name: <input type="text" id="last"><br>
Phone: <input type="text" id="phone"><br>
Mobile: <input type="text" id="mobile"><br>
Fax: <input type="text" id="fax"><br>
E-mail: <input type="text" id="email"><br>
Web: <input type="text" id="web"><br>
<input type="Submit">
</form>
here is my new edited script on output page =
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
//$("#dropdown-parent").on('change','#dropdown', function() { // replace dropdown-parent
$("#contacts").on('change','#dropdown', function() {
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
</script>
here is the php file for backgroundScript.php =
<?
// background script
// retrieve data based on $_POST variable, set to $returnArray
$returnArray = $_POST[array(
'first' => firstName,
'last' => lastName,
)];
/****************************
* the structure of returnArray should look something like
array(
'first' => firstName,
'last' => lastName,
)*/
echo json_encode($returnArray);
?>
this file will send in info so the javascript will then replace form fields with what ever is held in the areas appointed
It would appear that your PHP script is returning some formatted html, which you then try to insert into the dom via .val(). That method is used to set the values of form fields, not insert entire chunks of html. Try using .append() or .html() instead, plus do what Phil suggested above - split your script into multiple blocks.
You need to include your jQuery prior to using it:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
// Your Code Here
</script>
Better yet would be to use external JS:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="js/site.js"></script>
And if you're using HTML5 the type="text/javascript" isn't even needed so:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/site.js"></script>
Even better still would be to use a jQuery CDN:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="js/site.js"></script>
Also, as others have noted, be sure to use $ at the beginning of your jQuery factories. i.e. $('#dropdown')
-- Update --
Further clarification on project tree, most basic project trees look like this:
root/
|--css/
|--images/
|--js/
|--site.js
|--index.html
-- Update 2 --
Example of a $.post
$.post({
'somescript.php', // Script your posting to
{
someParam1: someData1, // $_POST['someParam1']
someParam2: someData2
// etc etc
},
function(response){
// Do something with JSON response upon successful post
alert(response);
},
'json' // Tells the script that JSON will be returned
});
-- Update 3 --
Okay so basically you want to do is...
Javascript:
var dropdown = $('#dropdown');
dropdown.bind('change', function(){
$post.(
'backgroundScript.php',
{
first: dropdown.val()
},
function(response) {
$('#first').val(response.first);
$('#last').val(response.last);
// Repeat for all of your form fields
},
'json'
);
});
Receive POST param:
$firstName = $_POST['first'];
MySQL query would be something like the following:
$sth = $dbh->prepare('SELECT *
FROM contacts
WHERE first = :first');
$sth->bindParam(':first', $first, PDO::PARAM_STR);
$sth->execute();
Then add all of your MySQL fields into associative array array(key => value) and then json_encode and return array.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$("#dropdown-parent").on('change','#dropdown', function() { // replace dropdown-parent
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
<script>
In your PHP you should have something like this
echo json_encode(array('first' => $some_value, 'last' => "Other value"));
Shouldn't
("#dropdown").on('change', function() {
be
$("#contacts").on('change', function() {

Categories