i use jqueryui for search in my site just like facebook
jquery code:
//search main
function split( val ) {
return val.split( );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#mainsearch" ).bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "/block/search.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
window.location.replace(ui.item.url);
// 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;
}
});
php code:
while($f = mysqli_fetch_array($s,MYSQLI_ASSOC)){
if($userid != $f['id']){
$name = $f['name'].' '.$f['family'];
$url = $siteurl.$f['username'].'/';
array_push($results, array('id' => $f['id'],'value' => $name,'url' => $url));
}
}
echo json_encode($results);
but if i insert image tag like:
<img src='something'>
its just show < img > text not an image when its show result
there is anyway to solve it?
thank you
From the jQuery-ui docs: "If you want the label to be treated as html you can use Scott González' html extension".
ok i solve this problem with code blow:
function split( val ) {
function extractLast( term ) {
return split( term ).pop();
}
$( "#mainsearch" ).autocomplete({
source: function( request, response ) {
$.getJSON( "/block/search.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
window.location.replace(ui.item.url);
// 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;
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li style='clear:both'>" )
.append( ""+item.value+"")
.appendTo( ul );
};return val.split( );
}
and php code:
while($f = mysqli_fetch_array($s,MYSQLI_ASSOC)){
if($userid != $f['id']){
$name = $f['name'].' '.$f['family'];$img = getimagesizes($f['image'],50);
$url = $siteurl.$f['username'].'/';
array_push($results, array('id' => $f['id'],'img' => $img,'value' => $name,'url' => $url));
}
}
echo json_encode($results);
.data must convert to html and show your result
as you can see in my qustion example in jqueryui is completely diffrent with this
but with this you can put html in your auto complete :)
Related
I have been using the jQuery ‘Autocomplete Widget’ for a number of years now. This has always been done but passing a value with ‘term’ to the PHP SQL code like this;
$( "#cs1" ).autocomplete({
autoFocus: true,
minLength: 3,
source: "gethint.php",
select: function( event, ui ) {
// This if undes the readonly on the Fname input field below
if ( ui.item.label == 'NONHAM' ) {$('#Fname').prop('readonly', false);}
$( "#cs1" ).val( ui.item.label );
$( "#hints" ).val( ui.item.value );
$( "#Fname" ).val( ui.item.desc );
var nc = $( "#thenetcallsign" ).html();
//return false;
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + " ---> " + item.desc + "</a>" )
.appendTo( ul );
};
});
But now I have to add another condition to the SQL code to return a more detailed value. The value for this additional condition is;
var nc = $( "#thenetcallsign" ).html();
The problem is I don’t know how to add this to ‘term’ or a separate variable and pass it to gethint.php using the ‘Autocomplete’ widget.
Once I get the extra value to the PHP program I know what to do.
Would somebody please explain or show me how to do this?
You might have to stringify it but pass the extraParams
extraParams: { type: "CoolCode" },
var nc = $("#thenetcallsign").html();
$("#cs1").autocomplete({
autoFocus: true,
minLength: 3,
source: "gethint.php",
extraParams: {
nc: nc
},
select: function(event, ui) {
// This if undes the readonly on the Fname input field below
if (ui.item.label == 'NONHAM') {
$('#Fname').prop('readonly', false);
}
$("#cs1").val(ui.item.label);
$("#hints").val(ui.item.value);
$("#Fname").val(ui.item.desc);
var nc = $("#thenetcallsign").html();
//return false;
}
})
.data("ui-autocomplete")._renderItem = function(ul, item) {
return $("<li>")
.append("<a>" + item.label + " ---> " + item.desc + "</a>")
.appendTo(ul);
};
});
source could be a function in order to get more flexibility
$( "#cs1" ).autocomplete({
/* ... */
source: function(request, response) {
$.getJSON( "gethint.php", {
term: request.term ,
nc: $( "#thenetcallsign" ).html()
}, response );
},
/* ... */
});
I need to send array to my mysql database.
I've created a JSON array and dont know how to post it to php to transfer to db.
$( function () {
$( '#orderForm' ).on( 'submit', function ( event ) {
event.preventDefault();
var myData = [],
keys = ['item', 'qty', 'price'],
url = this.action;
$( '#orderTable' ).find( 'tr:gt(0)' ).each( function ( i, row ){
var oRow = {};
$( row ).find( 'td' ).each( function ( j, cell ) {
oRow[keys[j]] = $( cell ).text();
} );
myData.push( oRow );
} );
console.log( myData );
console.log( JSON.stringify( myData ) );
} );
} );
I need to post it item->item, qty->qty, price->price to the db.
I've tried :
$.ajax( {
url: 'tc_menu',
type: 'POST',
data: JSON.stringify( myData ),
success: function ( data ) {
console.log( "success:", data );
},
failure: function ( errMsg ) {
console.error( "error:", errMsg );
}
} );
Data stores whole page, but not (stringified myData). And I still cant get it at php code by $_POST and json_decode
Data stores whole page, but not stringified myData and I can't get it at php code by $_POST and json_decode
php code
`if(isset($_POST['submitted_m'])){
$myData = serialize($_POST['data']);
$sqli = "INSERT INTO tc_cafe_orders SET item='".$myData."' ";
if (mysqli_query($db, $sqli)) {
$msg = "New Order added!";
echo "<script>
alert(\"$msg\");
window.location.replace('tc_menu.php');
</script>";}
else {echo "Error:".$sql."<br>".mysqli_error($db);}}`
Try this one for js
$(function () {
$('#orderForm').on( 'submit', function ( event ) {
event.preventDefault();
var myData = [],
keys = ['item', 'qty', 'price'],
url = this.action;
$( '#orderTable' ).find( 'tr:gt(0)' ).each( function ( i, row ){
var oRow = {};
$( row ).find( 'td' ).each( function ( j, cell ) {
oRow[keys[j]] = $( cell ).text();
} );
myData.push( oRow );
} );
console.log( myData );
console.log( JSON.stringify( myData ) );
data_to_server = JSON.stringify(myData);
});
$.post("*your_php_file*", {
data: data_to_server;
}).done(function (data_returned) {
// any your code
});
});
And seems you have mismatch in PHP code - trying to serialize() instead of json_decode()
Remove nested click event and closure.
e.g.
$( '#orderForm' ).on( 'submit', function ( event ) {
$( '#orderForm' ).on( 'submit', function ( event ) {
} );
} );
Than try again.
And your MySQL insert statement in php
$sqli = "INSERT INTO tc_cafe_orders SET item='".$myData."' ";
is not ok.
Learn more about MySQL insert statement here https://www.w3schools.com/php/php_mysql_insert.asp
I have tried following code picked from plunker to reduce ajax request to database. JSON format is also generated fine as per example in text file.
But when i'am trying to populate autocomplete options it's showing only one character of beginning. But when i use json output directly with items variable then it works fine.
Plunker
Plunker Link
JSON example in Keywords.txt file
["Mis","Operation","Operation Manager","Php","Sales","Telecalling","Analytics","Ceo","Commercials"];
Code
$(function()
{
var items = 'Keywords.txt';
function split( val )
{
return val.split( /,\s*/ );
}
function extractLast( term )
{
return split( term ).pop();
}
$( "#keyword" )
.autocomplete(
{
minLength: 1,
source: function( request, response )
{
response( $.ui.autocomplete.filter(items, extractLast( request.term ) ) );
},
focus: function()
{
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;
}
});
});
I think that your problem is that you have a string, try to parse the response:
$.get('Keywords.txt').then(function(keywords){
items = JSON.parse(keywords);
});
I'm using the jQuery combobox widget which works fine, but is causing some issues when added dynamically.
What should happen
Visitor uses the combobox to filter/select valid users to add to a
list.
The list has no max number of users that can be added.
There's a [+] toggle button at the end of each user field that allows the Visitor to add another user to the list.
Clicking the button makes an ajax call to add more users to the list, allowing there to be no limit to the max number of users.
Initially, 10 user fields are loaded on screen, and then when they click the [+] button towards the end, the ajax call adds another 10 to the list.
What's Happening
When the form with the list of users is submitted, the users from the initial 10 fields appear fine, but any fields added as part of the ajax call are returned as empty.
Here's the code:
combobox:
(function( $ ) {
$.widget( "ui.combobox", {
_create: function() {
var input,
that = this,
wasOpen = false,
select = this.element.hide(),
selected = select.children( ":selected" ),
value = selected.val() ? selected.text() : "",
wrapper = this.wrapper = $( "<span>" )
.addClass( "ui-combobox" )
.insertAfter( select );
function removeIfInvalid( element ) {
var value = $( element ).val(),
matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( value ) + "$", "i" ),
valid = false;
select.children( "option" ).each(function() {
if ( $( this ).text().match( matcher ) ) {
this.selected = valid = true;
return false;
}
});
if ( !valid ) {
}
}
input = $( "<input>" )
.appendTo( wrapper )
.val( value )
.addClass( "ui-state-default ui-combobox-input " )
.autocomplete({
delay: 0,
minLength: 0,
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( select.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: text,
option: this
};
}) );
},
select: function( event, ui ) {
ui.item.option.selected = true;
that._trigger( "selected", event, {
item: ui.item.option
});
},
change: function( event, ui ) {
if ( !ui.item ) {
removeIfInvalid( this );
}
}
})
.addClass( "ui-widget ui-widget-content ui-corner-left" );
input.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
// .tooltip()
.appendTo( wrapper )
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-combobox-toggle" )
.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", "" );
});
// input.tooltip({
// // tooltipClass: "tool_toplft"
// });
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
})( jQuery );
ajax code:
$('body').on('click','.add_usr', function(){
if($('.box.noshow').length == 3){
$(this).fadeOut(800);
var count = parseInt($(this).attr('data-ctr')) +1;
$.post('/base/process.php', {action: 'team_add_usr_select', 'count': count}, function(data){
$('.box:last').after(data.output);
});
}
$('.box.noshow').first().fadeIn(800).removeClass('noshow');
$('.box').children('select').removeAttr('disabled');
$('.box.noshow').each(function(){
$(this).children('select').attr('disabled', 'disabled');
});
$('.add_usr').css('display','none');
$('.box:visible').last().children('.add_usr').css('display','inline-block');
if($('.box:visible').length > 1){
$('.del_usr').css('display', 'inline-block');
}
return false;
});
Again, the combobox is working correctly, but when I submit the form, the fields are present but blank.
UPDATE
data outputs an object with the details for me, including the original form information.Here's an example of the output:
form: Object
form: "team_add"
id_leader: "1"
id_team: ""
team_name: "test"
usr: Object
1: "1"
2: "13"
3: "521"
4: "533"
5: "2"
6: "3"
7: "816"
This example was sent with 12 users added. The new fields are added to the form after entry #7 is filled and clicked. Also, I've noticed in this instance it stopped showing additional fields. Previously when testing, it would list 8: "". Now I'm more confused.
i am trying to implement an autocomplete combobox using jquery ui plugin.
with the below mentioned code i am able to achieve the autocomplete part but not the dropdown part (due to the uncaught typeerror the dropdown arrow is not visible)
$.widget( "ui.combobox", {
_create: function() {
var input,
self = this,
select = this.element.hide(),
selected = select.children( ":selected" ),
value = selected.val() ? selected.text() : "",
wrapper = this.wrapper = $( "<span>" )
.addClass( "ui-combobox" )
.insertAfter( select );
input = $( "<input>" )
.appendTo( wrapper )
.val( value )
.addClass( "ui-state-default ui-combobox-input" )
.autocomplete({
delay: 0,
minLength: 0,
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( select.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: text,
option: this
};
}) );
},
select: function( event, ui ) {
ui.item.option.selected = true;
self._trigger( "selected", event, {
item: ui.item.option
});
},
change: function( event, ui ) {
if ( !ui.item ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
valid = false;
select.children( "option" ).each(function() {
if ( $( this ).text().match( matcher ) ) {
this.selected = valid = true;
return false;
}
});
if ( !valid ) {
// remove invalid value, as it didn't match anything
$( this ).val( "" );
select.val( "" );
input.data( "autocomplete" ).term = "";
return false;
}
}
}
})
.addClass( "ui-widget ui-widget-content ui-corner-left" );
input.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.appendTo( wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-combobox-toggle" )
.click(function() {
// close if already visible
if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
input.autocomplete( "close" );
return;
}
// work around a bug (likely same cause as #5265)
$( this ).blur();
// pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
input.focus();
});
},
destroy: function() {
this.wrapper.remove();
this.element.show();
$.Widget.prototype.destroy.call( this );
}
});
$( "#combobox" ).combobox();
The above code is under document.ready.
The error is thrown due to '.button' method.
The html:
<tr>
<td><label>Country:</label></td>
<td>
<div class="ui-widget">
<select id="combobox">
<option value="">Select one...</option>
<option value="ActionScript">ActionScript</option>
<option value="AppleScript">AppleScript</option>
<option value="Asp">Asp</option>
<option value="BASIC">BASIC</option>
<option value="C">C</option>
</select>
</div>
</td>
</tr>
combobox css,
.ui-combobox {
position: relative;
display: inline-block;
}
.ui-combobox-toggle {
position: absolute;
top: 0;
bottom: 0;
margin-left: -1px;
padding: 0;
/* adjust styles for IE 6/7 */
*height: 1.7em;
*top: 0.1em;
}
.ui-combobox-input {
margin: 0;
padding: 0.3em;
}
The script sequence is,
<script type="text/javascript" src="<?php echo base_url('/assets/js/jquery.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('/assets/js/validation.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('/assets/autocomplete/js/jquery-ui-1.8.21.custom.min.js'); ?>"></script>
<?= $_scripts ?>
jquery version 1.7.2, jquery ui version 1.8.21
i have tried rearranging the sequence of the scripts
there are no multiple instances of different jquery versions.
Any help would be appreciated. Thanks!
Your code looks fine so the problem is almost certainly that you didn't include ui.button in your custom jQuery UI build.
You can verify this by running typeof $.ui.button. If you have it included it will be function, if you do not it will be undefined.
Re-build jQuery UI and make sure to select the Button checkbox.