I'm using PHP, MySQL, Smarty, jQuery, AJAX, etc. for my website. Now I'm trying to make one input field(having id user_name) autocomplete enabled. I want to give the user suggestions when he starts typing into the input field. I'm passing the value typed in by user as an argument, fetching the suggestions from MySQL database based on the argument recieved, converting the fetched database records into json response and trying to show it as a suggestion to the user. But unfortunately I'm not able to show the suggestions I received in json format to the user as he types in. If I observe in firbug, the request is going properly, the json response is also receiving properly but not getting displayed below the textfield as a suggestion. Also there are no errors found in the firebug console. For your reference I'm putting the code below. The HTML(code from smarty) part:
我在我的网站上使用PHP,MySQL,Smarty,jQuery,AJAX等。现在我正在尝试启用一个输入字段(具有id user_name)自动完成功能。我想在用户输入输入字段时给出用户建议。我将用户输入的值作为参数传递,根据收到的参数从MySQL数据库中获取建议,将获取的数据库记录转换为json响应,并尝试将其显示为对用户的建议。但不幸的是,当我输入时,我无法向用户显示我收到的json格式的建议。如果我在firbug中观察,请求正常,json响应也正常接收但未显示在文本字段下方作为一个建议。此外,在firebug控制台中没有发现错误。供您参考我将下面的代码。 HTML(来自smarty的代码)部分:
<html>
<head>
<link rel="stylesheet" type="text/css" href="{$control_css_url}ui-lightness/jquery-ui-1.10.3.custom.css">
<link rel="stylesheet" type="text/css" href="{$control_css_url}autocomplete.css">
<script src="{$control_js_url}vendor/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="{$control_js_url}jquery-ui/jquery-ui-1.10.3.custom.min.js"></script>
</head>
<body>
<form id="view-student_result-form" name="view_student_result" action="{$control_url}modules/reports/report_student_result.php" method="post">
<input type="hidden" name="op" id="op" value="get_student_result" >
<div class="w50">
<ul>
<li>
<label>Class</label>
<div class="form-element">
<select name="class_id" id="class_id" onchange="get_section_by_class(this.value, 'get_section_by_class', '#section_id'); return false;">
<option value="">-Select Class-</option>
{foreach from=$all_class item=class key=key}
<option value="{$class.group_id}" {if $class_id == $class.group_id} selected="selected"{/if}>{$class.group_name}</option>
{/foreach}
</select>
</div>
</li>
<li>
<label>Name</label>
<div class="form-element" id="friends" class="ui-helper-clearfix">
<input type="text" class="" name="user_name" id="user_name" value="{$user_name}" />
</div>
</li>
<li>
<label>Section</label>
<div class="form-element">
<select name="section_id" id="section_id">
{if empty($section_id)}
<option value="">-Select Section-</option>
{else}
<option value="all">All</option>
{/if}
{foreach from=$all_section_by_class item=section key=key}
<option value="{$section.group_id}" {if $section_id==$section.group_id} selected="selected"{/if}>{$section.group_name}</option>
{/foreach}
</select>
</div>
</li>
</ul>
</div>
</form>
</body>
</html>
{literal}
<script language="javascript" type="text/javascript">
$(function() {
//attach autocomplete
$("#user_name").autocomplete({
//define callback to format results
source: function(req, add) {
var class_id = $('#class_id').val();
var section_id = $('#section_id').val();
//pass request to server
$.getJSON("report_student_result.php?callback=?&op=get_student_names&class_id="+class_id+"§ion_id="+section_id, req, function(data) {
//create array for response objects
var suggestions = [[]];
//process response
$.each(data, function(i, val){
suggestions.push(val.name);
});
//pass array to callback
add([suggestions]);
});
},
//define select handler
select: function(e, ui) {
//create formatted friend
var friend = ui.item.value,
span = $("<span>").text(friend),
a = $("<a>").addClass("remove").attr({
href: "javascript:",
title: "Remove " + friend
}).text("x").appendTo(span);
//add friend to friend div
span.insertBefore("#user_name");
},
//define select handler
change: function() {
//prevent 'user_name' field being updated and correct position
$("#user_name").val("").css("top", 2);
}
});
//add click handler to friends div
$("#friends").click(function(){
//focus 'user_name' field
$("#user_name").focus();
});
//add live handler for clicks on remove links
$('#friends').on("click", ".remove", document.getElementById("friends"), function(){
//$(".remove", document.getElementById("friends")).live("click", function(){
//remove current friend
$(this).parent().remove();
//correct 'user_name' field position
if($("#friends span").length === 0) {
$("#user_name").css("top", 0);
}
});
});
</script>
{/literal}
Now the code from PHP file(one case from the file report_student_result.php):
现在来自PHP文件的代码(来自文件report_student_result.php的一个案例):
<?php
global $gDb;
$op = $request['op'];
switch($op) {
case'get_student_names':
$param = $_GET["term"];
$group_id = $request['class_id'];
if($request['section_id'] !='all')
$group_id = $request['section_id'];
if ($group_id != '') {
$sql =" SELECT u.user_id, CONCAT(u.user_first_name, ' ', u.user_last_name) as full_name ";
$sql .=" FROM ".TBL_USERS." as u JOIN ".TBL_USERS_GROUPS_SUBSCRIBE." as ugs ON u.user_id = ";
$sql .=" ugs.subscribe_user_id WHERE ugs.subscribe_group_id = ".$group_id." AND (u.user_first_name ";
$sql .=" REGEXP '^$param' OR u.user_last_name REGEXP '^$param')";
} else {
$sql =" SELECT user_id, CONCAT(user_first_name, ' ', user_last_name) as full_name ";
$sql .=" FROM ".TBL_USERS." WHERE user_first_name REGEXP '^$param' OR user_last_name ";
$sql .=" REGEXP '^$param'";
}
$gDb->Query( $sql );
$data = $gDb->FetchArray();
$response = $_GET["callback"] . "(" . json_encode($data) . ")";
echo $response;
die;
}
?>
If you want anything more information like the json response I'm receiving while user types in the text, I can provide you. The above code is working fine, the only issue is in displaying the suggestions received under the textfield having id user_name. Please help me to resolve this issue. Looking forward to your replies. Thanks in advance.
如果您想要更多信息,例如我在文本中输入用户时收到的json响应,我可以为您提供。上面的代码工作正常,唯一的问题是显示在具有id user_name的文本字段下收到的建议。请帮我解决这个问题。期待您的回复。提前致谢。
2 个解决方案
#1
0
You can try this out. I think it will definitely solve your issue of displaying the json response values properly.
你可以尝试一下。我认为它肯定会解决你正确显示json响应值的问题。
<script language="javascript" type="text/javascript">
$(function() {
$( "#user_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "report_student_result.php",
dataType: "json",
data: {
request_type: "ajax",
op: "get_student_names",
class_id: $('#class_id').val(),
section_id: $('#section_id').val(),
name_startsWith: request.term
},
success: function( data ) {
response(
$.map(data, function(item) {
return {
label: item.full_name,
value: item.full_name
}
})
);
}
});
},
minLength: 2,
select: function( event, ui ) {
if(ui.item) {
$(event.target).val(ui.item.value);
}
return false;
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
</script>
#2
0
<!--For location search start-->
<link rel="stylesheet" href= "http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
.ui-autocomplete-category {
font-weight: bold;
padding: .2em .4em;
margin: .8em 0 .2em;
line-height: 1.5;
}
</style>
<script>
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this,
currentCategory = "";
$.each( items, function( index, item ) {
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
that._renderItemData( ul, item );
});
}
});
</script>
<script>
$(function() {
var data = [
<?php
$sql_all_location="SELECT LocationId,LocationName,ParentLocationId FROM wp_location_master WHERE LocationLevel<7";
$query_all_location=mysql_query($sql_all_location);
while($fetch_all_location=mysql_fetch_assoc($query_all_location))
{
$sql_parent_location="SELECT LocationName FROM wp_location_master WHERE LocationId='".$fetch_all_location['ParentLocationId']."'";
$query_parent_location=mysql_query($sql_parent_location);
$fetch_parent_location=mysql_fetch_assoc($query_parent_location);
?>
{ label: "<?php echo $fetch_all_location['LocationName'];?>", category: "<?php echo $fetch_parent_location['LocationName']; ?>" },
<?php
}
?>
];
$("#search").catcomplete({
delay: 0,
source: data
});
});
</script>
<!--For location search end-->
#1
0
You can try this out. I think it will definitely solve your issue of displaying the json response values properly.
你可以尝试一下。我认为它肯定会解决你正确显示json响应值的问题。
<script language="javascript" type="text/javascript">
$(function() {
$( "#user_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "report_student_result.php",
dataType: "json",
data: {
request_type: "ajax",
op: "get_student_names",
class_id: $('#class_id').val(),
section_id: $('#section_id').val(),
name_startsWith: request.term
},
success: function( data ) {
response(
$.map(data, function(item) {
return {
label: item.full_name,
value: item.full_name
}
})
);
}
});
},
minLength: 2,
select: function( event, ui ) {
if(ui.item) {
$(event.target).val(ui.item.value);
}
return false;
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
</script>
#2
0
<!--For location search start-->
<link rel="stylesheet" href= "http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
.ui-autocomplete-category {
font-weight: bold;
padding: .2em .4em;
margin: .8em 0 .2em;
line-height: 1.5;
}
</style>
<script>
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this,
currentCategory = "";
$.each( items, function( index, item ) {
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
that._renderItemData( ul, item );
});
}
});
</script>
<script>
$(function() {
var data = [
<?php
$sql_all_location="SELECT LocationId,LocationName,ParentLocationId FROM wp_location_master WHERE LocationLevel<7";
$query_all_location=mysql_query($sql_all_location);
while($fetch_all_location=mysql_fetch_assoc($query_all_location))
{
$sql_parent_location="SELECT LocationName FROM wp_location_master WHERE LocationId='".$fetch_all_location['ParentLocationId']."'";
$query_parent_location=mysql_query($sql_parent_location);
$fetch_parent_location=mysql_fetch_assoc($query_parent_location);
?>
{ label: "<?php echo $fetch_all_location['LocationName'];?>", category: "<?php echo $fetch_parent_location['LocationName']; ?>" },
<?php
}
?>
];
$("#search").catcomplete({
delay: 0,
source: data
});
});
</script>
<!--For location search end-->