Help me to solve problem with jQuery and PHP - php

I want to apply "Jquery UI Autocomplete with multiple values" to one registration forms input field.
What i want to do exactly: When visitor types name of existing user to this input field, first of all, script searches for name existence, completes it (if exists), adds comma. User can type second, third... existing usernames to this field, and everytime script will auto complete. And when visitor clicks to submit button, PHP searches for id's of this usernames, creates array of id's, adds it to new users "friends" field in db table.
My code:
HTML
<form action="index.php" method="post">
<input class="std" type="text" name="friends" id="friends"/>
<input type="submit" name="submit">
</form>
Jquery
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( termĀ ).pop();
}
$( "#friends" )
// 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;
}
});
});
search.php
$conn = mysql_connect("localhost", "user", "pass") or die( mysql_error() );;
mysql_select_db("db", $conn) or die( mysql_error() );;
$q = strtolower($_GET["term"]);
if (!$q) return;
$query = mysql_query("select id, fullname from usr_table where fullname like '$q%'") or die(mysql_error());
$results = array();
while ($row = mysql_fetch_array($query)) {$results[] = array ( "id" => $row[0] , "label" => $row[1], "value" => $row[1] );}
echo json_encode($results);
My questions:
I need only id of written name,
and fullname. I don't need value.
How can i delete it from jquery
code?
how to fetch array of id's
of written names, and put to
"friends" field of usr_table after
submission of registration form?
And finally i want to realise it
with mysqli. Which parts of code i
must change?
Sorry for my bad
english

This autocompleter can do what you want:
http://www.devbridge.com/projects/autocomplete/jquery/#demo
Just try to type country names separated by commas. I use it on my webpages and works well.

Related

jQuery Autocomplete ComboBox Options Echo'd by PHP Getting Removed when Match Typed

Currently I have a combobox which options gets echo'd by PHP since the values are in an array. The code of the combobox is as follows:
<div class="ui-widget">
Project
<br>
<select id="combobox">
<?php
foreach($projects as $value)
{
echo "<option value=".$value.">".$value."</option>";
}
?>
</select>
</div>
What I am trying to achieve is when a user types into the combobox he gets a dropdown-list with all the entries of the array that match the text the user typed in the combobox.
The user can then select an option from the dropdown-list or choose to type the entry completely(but it needs to mach the entries in the dropdown-list).
To achieve all this i am currently using the Autocomplete function of jQuery.
All the code that I am using to achieve this can be watched here: http://jqueryui.com/autocomplete/#combobox.
The code for the combobox I use is as follows:
<script>
(function( $ ) {
$.widget( "custom.combobox", {
_create: function() {
this.wrapper = $( "<span>" )
.addClass( "custom-combobox" )
.insertAfter( this.element );
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function() {
var selected = this.element.children( ":selected" ),
value = selected.val() ? selected.text() : "";
this.input = $( "<input>" )
.appendTo( this.wrapper )
.val( value )
.attr( "title", "" )
.addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy( this, "_source" )
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on( this.input, {
autocompleteselect: function( event, ui ) {
ui.item.option.selected = true;
this._trigger( "select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function() {
var input = this.input,
wasOpen = false;
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.tooltip()
.appendTo( this.wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "custom-combobox-toggle ui-corner-right" )
.mousedown(function() {
wasOpen = input.autocomplete( "widget" ).is( ":visible" );
})
.click(function() {
input.focus();
// Close if already visible
if ( wasOpen ) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
});
},
_source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( this.element.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text,
value: text,
option: this
};
}) );
},
_removeIfInvalid: function( event, ui ) {
// Selected an item, nothing to do
if ( ui.item ) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children( "option" ).each(function() {
if ( $( this ).text().toLowerCase() === valueLowerCase ) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if ( valid ) {
return;
}
// Remove invalid value
this.input
.val( "" )
.attr( "title", value + " didn't match any item" )
.tooltip( "open" );
this.element.val( "" );
this._delay(function() {
this.input.tooltip( "close" ).attr( "title", "" );
}, 2500 );
this.input.autocomplete( "instance" ).term = "";
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
})( jQuery );
$(function() {
$( "#combobox" ).combobox();
$( "#toggle" ).click(function() {
$( "#combobox" ).toggle();
});
});
</script>
The problem that I am having right now is when a user types text in the combobox and the dropdown-list appears and he fully types out an entry of the dropdown-list the combobox still gets cleared. This is not supposed to happen. Whenever the user clicks on the combobox the item doesn't get cleared.
To make is a bit clearer here is an image of the combobox:
So above you can see the combobox. Whenever a user types something he gets a dropdown-list with all the results matched(project 1, project 10).
The problem that I am having right now is when a user types out "project 1" without clicking on the item in the dropdown-list the text in the combobox still gets removed by the Autocomplete function in jQuery.
If the user clicks on the item then there is no problem at all.
Funny thing is that the Autocomplete function works without any problems if I don't echo the option elements with PHP.
so:
<option value="project 1">project 1</option>
<option value="project 2">project 2</option>
<option value="project 3">project 3</option>
instead of:
foreach($projects as $value)
{
echo "<option value=".$value.">".$value."</option>";
}
Any help is greatly appreciated.
Change from
echo "<option value=".$value.">".$value."</option>";
TO
echo "<option value='".$value."'>".$value."</option>";

How To Add Validation in Textbox in Jquery

What I need:
When User Enter a mail address in text box then commas (,) should Seprate email address.
i have used Example of jquery Autocomplete here is the url:http://jqueryui.com/autocomplete/#multiple.
i want that user enter multiple email address in textbox and (,) should seperate each email address.
here is the snapshot that i want :http://postimg.org/image/z7tv89bab/
$(function() {
var availableTags = [
"af#gmail.com",
"af1#gmail.com",
"af2#gmail.com",
"af3#gmail.com",
];
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#tags" )
// 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( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
availableTags, extractLast( request.term ) ) );
},
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;
}
});
});
Tag programming languages:
Try jquery validation plugin to validate textbox.
// Code to accept multile mails
jQuery.validator.addMethod("multiemail", function (value, element) {
if (this.optional(element)) {
return true;
}
var emails = value.split(','),
valid = true;
for (var i = 0, limit = emails.length; i < limit; i++) {
value = emails[i];
valid = valid && jQuery.validator.methods.email.call(this, value, element);
}
return valid;
}, "Invalid email format: please use a comma to separate multiple email addresses.");
The above function should be used in validation js
var validator = $("#frmlogin").validate({
errorElement: 'div',
rules: {
email: {
required: true,
email: true,
multiemail: true
}
});

how to pass hidden id using json in jquery ui autocomplete?

perhaps it is duplicate,but i can't found solution so i posted this question.I am use jquery ui for auto complete search box. it works fine but the problem is i want to search using id.example:when user type paris,i try to send city_id in mysql for search. so problem is how to pass hidden id with json?
here the code:
<input type="text" name="grno" id="grno" class="input" title="<?php echo $lng['vldgrno'];?>
jquery code:
<script>
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#grno" )
// 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( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "pages/search.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 1 ) {
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( "," );
alert(data.id);
return false;
}
});
});
</script>
autocomplete.php :
<?php
mysql_connect('localhost','root','');
mysql_select_db('school');
$return_arr = array();
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends
//create select query
$query = "select `grno`,`first_name`,`student_id` from `tbl_student` where `grno` like '%".$term."%' or `first_name` like '%".$term."%'";
// Run the query
$result = mysql_query ($query);
$array = array();
while($obj = mysql_fetch_array($result)){
$array['name'] = $obj['first_name']."(".$obj['grno'].")";
array_push($return_arr,$obj['first_name']."(".$obj['grno'].")");
}
$json = json_encode($return_arr);
echo $json;
?>
so.how to pass student_id in autocomplete.php,like label and value.{label='xyz' value='1'}
In autocomplete.php replace this code
array_push($return_arr,array("value"=>$obj['student_id'],"label"=>$obj['first_name']."(".$obj['grno'].")"));
and in your script change this
terms.push( ui.item.label );
$( "#stud_id" ).val( ui.item.value );
hope,this is what you find.

How to Save Multiple Values in jQuery Autocomplete to MySQLi DB?

I'm just learning about the jQuery AutoComplete Widget. The values pop up with a comma nicely. So, the visual display to the user is great.
My issue is how do I save the multiple values to a MySQLi database?
Here is the code:
<script>
$(function() {
var availableskills = [
"ActionScript",
"AppleScript",
..........
more languages
"XML"
];
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#skills" )
// 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({
minLength: 0,
// could have source as a "url"
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
availableskills, extractLast( request.term ) ) );
},
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>
Now, here's my input id for letting the user select the skills:
<div class="ui-widget">
<!--<label for="skills">Tag programming languages: </label>-->
<input type="text" id="skills" size="50" />
</div>
Not sure on how to save the skills the user selects into a database. I can save data to a MySQLi db with ease; the issue is how can I take say three skills and save them into three different rows in a table in a database.
Any help, very much appreciated.
Ken
for example you will do form post with the input name skills
<form method="post" action="test.php">
<div class="ui-widget">
<input type="text" id="skills" size="50" name='skills' />
</div>
</form>
then test.php would be something like
<?php
//...do some mysql connections
$skills = explode(",",$_POST['skills']);
foreach($skills as $skill){
$statement.="INSERT INTO blahblahblah SET skill = ".mysqli_real_escape_string($skill);
}
$mysqli->multi_query($statement);

php, Jquery autocomplete multiple values, remote!

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);
?>

Categories