I am using jQuery AutoComplete to fetch results from a DataBase based on the value inputted. The user will then click a search button to tell the page to search for that specific entries details.
I want to get 2 values, the Name and Title. I only want to display the Name to the user, while the page uses the Title as a search criteria.
eg: When a person types in Vehicle, the result will display Vehicle1, Vehicle2 in a list.
When the user clicks on Vehicle1, a hidden box will be issues with the Title, which would be Bike, and such as with Vehicle2, which will issue the hidden box with Car.
I can get the Name to show in the text box properly, but I cannot for the life of me (And after 2 days of searching) bind the Title to a hidden box.
JavaScript:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".tb").autocomplete({
source: function (request, response) {
$.ajax({
url: "AutoComplete.asmx/FetchEmailList",
data: "{ 'prefix': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
//value: item.Title,
label: item.Name
};
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
ASPX Code:
<div class="ui-widget" >
<asp:TextBox ID="tbAuto" class="tb" runat="server">
</asp:TextBox>
<asp:TextBox runat="server" ID="tbHidden" class="tb"></asp:TextBox>
</div>
CodeBehind:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class AutoComplete : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Employee> FetchEmailList(string prefix)
{
var emp = new Employee();
var fetchEmail = emp.GetEmployeeList(prefix)
.Where(m => m.Name.ToLower().StartsWith(prefix.ToLower()));
return fetchEmail.ToList();
}
}
CompletionClass: (Excuse the naming)
public class Employee
{
public string Title { get; set; }
public string Name { get; set; }
public string value { get; set; }
public List<Employee> GetEmployeeList(string prefixText)
{
List<Employee> cmpList = new List<Employee>();
SqlConnection db = DataConn.SqlConnection();
db.Open();
SqlTransaction transaction = db.BeginTransaction();
//var array = new ArrayList();
try
{
SqlCommand command = new SqlCommand("Select [something] FROM vwGetDetails WHERE [something_else] LIKE N'%" + prefixText + "%' ORDER BY [thatOther_thing] ASC", db, transaction);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
cmpList.Add(new Employee() { Name = reader["Value1"].ToString(), Title = "Value1_Cat", value = "Value1_Cat"});
}
}
command = new SqlCommand("Select [something] FROM [somewhere] WHERE [thingy] LIKE N'%" + prefixText + "%' ORDER BY [previousThingy] ASC", db, transaction);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
cmpList.Add(new Employee() { Name = reader["Value2"].ToString(), Title = "Value2_Cat", value = "Value2_Cat"});
}
}
transaction.Commit();
}
catch (SqlException)
{
transaction.Rollback();
cmpList.Add(new Employee() { Name = "Problem Getting Results.", value = "Error"});
//array.Add("Problem Getting Results.");
}
if (cmpList.Count == 0)
cmpList.Add(new Employee() { Name = "Nothing to Display.", value = "Info"});
//array.Add("Nothing to Display.");
//return array;
return cmpList;
}
}
Those modifications to your JavaScript should do the trick:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('input[name$="tbAuto"]').autocomplete({
source: function (request, response) {
$.ajax({
url: "AutoComplete.asmx/FetchEmailList",
data: "{ 'prefix': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response(data.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
focus: function(event, ui) {
$('input[name$="tbAuto"]').val(ui.item.Name);
return false;
},
select: function(event, ui) {
$('input[name$="tbAuto"]').val(ui.item.Name);
$('input[name$="tbHidden"]').val(ui.item.Title);
return false;
}
}).data('autocomplete')._renderItem = function(ul, item) {
return $('<li>').data('item.autocomplete', item).append('<a>' + item.Name + '</a>').appendTo(ul);
};
});
</script>
The assumption here is that the selectors returns exactly the element which we are working on, if not they need to be adjusted.
Cool. I've been googling for this solution for days... excellent clean code!
Just a small remark: using jqueryUI 1.10, this
throws javascript exception.
.data('autocomplete')._renderItem = function(ul, item) {...
I've used
.data('ui-autocomplete')._renderItem = function(ul, item) {...
and everything works great.
Related
this code does not work. what should i do please help me there is no problem in database i couldn't find the solution
Is there a problem with WebMethod? I did everything but there is something I can't see
I'm stuck on this, my project is waiting for this
I will be very grateful to the friend who solved this
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static List<ChartDetails> GetPiechartData()
{
List<ChartDetails> dataList = new List<ChartDetails>();
string sConnString = "Data Source=.;Initial Catalog=deneme;Integrated Security=True";
SqlConnection baglanti = new SqlConnection(sConnString);
SqlCommand cmd = new SqlCommand("select begeni , kontrolid from yorum", baglanti);
baglanti.Open();
SqlDataReader droku = cmd.ExecuteReader();
while (droku.Read())
{
dataList.Add(new ChartDetails
{
kontrolid = droku["kontrolid"].ToString(),
begeni = Convert.ToInt32(droku["begeni"]),
});
}
return dataList;
}
public class ChartDetails
{
public string kontrolid { get; set; }
public int begeni { get; set; }
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.charts.load('current', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
</script>
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Default17.aspx/GetPiechartData",
data: "{}",
success: function (response) {
drawchart(response.d);
},
error: function () {
alert("Error loading data...........");
}
});
})
function drawchart(dataValues) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'kontrolid');
data.addColumn('number', 'begeni');
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].kontrolid, dataValues[i].begeni]);
}
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curvechart'));
chart.draw(data, options);
}
</script>
I have a problem displaying the data in the dropdown list using select2. I think the reason is the Query returning many rows. when I limit the number of Row to 50 (where Rownum <=100 ) the data displayed but when I remove the where condition no data display. The PatientDemo table has more than 600000 rows Any help how to solve this issue. I am using Orcale and C#
View
<link href="~/Content/css/select2.min.css" rel="stylesheet" />
<div class="jumbotron">
<input type="hidden" id="textBoxVal" />
<select class="mySelect2" style="width:500px;">
</select>
</div>
<script>
$(document).ready(function () {
$(".mySelect2").select2({
placeholder: "Select category",
allowClear: true,
theme: "classic",
ajax: {
url: "/Home/GetCategory",
dataType: 'json',
delay: 10000,
data: function (params) {
return {
searchTerm: params.term
};
},
processResults: function (data, params) {
return {
results: data
};
}
}
});
});
$(".mySelect2").on("change", function () {
var catId = $(this).val();
$("#textBoxVal").val(catId);
var textBoxValueData = $("#textBoxVal").val();
$.ajax({
url: '/Home/Save?data=' + textBoxValueData,
dataType: 'json',
type: 'post',
});
});
Model
public class Select2Model
{
public string id { get; set; }
public string text { get; set; }
}
C#
public JsonResult GetCategory(string searchTerm)
{
var list = new List<Select2Model>();
using (OracleConnection conn = new OracleConnection(WebConfigurationManager.ConnectionStrings["PatientRecord"].ConnectionString))
{
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = #"SELECT PATIENT, NAMEFORWARD FROM PATIENTDEMO ";
cmd.CommandType = CommandType.Text;
OracleDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
list.Add(new Select2Model()
{
text = rdr["NAMEFORWARD"].ToString(),
id = rdr["Patient"].ToString()
});
}
var dataList = list.ToList();
if (searchTerm != null)
{
dataList = list.Where(x => x.text.Contains(searchTerm)).ToList();
}
var modifiedData = dataList.Select(x => new {
id = x.id,
text = x.text
});
return Json(modifiedData, JsonRequestBehavior.AllowGet);
}
}
public JsonResult Save(string data)
{
return Json(0, JsonRequestBehavior.AllowGet);
}
600000 rows in a drop down list is not a user friendly one. Instead why don't you implement a drop down list with auto complete?
Check the example at the bottom of this page: https://api.jqueryui.com/autocomplete/
Update:
In your case you source would be a ajax call to the server side to pull the relevant data. Like this:
$('#myautocomplete').autocomplete({
type: "POST",
minLength: 3,
source : function (request, response)
{
var source_url = "../handlers/MyLookup.ashx?someparameter=" + $("#someparameter").val();
$.ajax({
url: source_url,
dataType: "json",
data: request,
success: function (data) { response(data); },
error : function (a,b,c) { HandleLookUpError(a); }
});
},
select: function (event, ui) { $('#result').val(ui.item.id); }
});
Note the source_url variable and the ajax call in the above code.
More details on how to load data from server side is here: https://stackoverflow.com/a/8873641/218408
I cannot get autocomplete to work. I suspect this is because of my declaration of the URL in the Jquery method. How can I fix this issue?
This is the method in the HomeController:
public JsonResult Autocomplete(string term)
{
string connectionString = ConfigurationManager.ConnectionStrings["AbintegroModelContext"].ConnectionString;
List<string> CompanyName = new List<string>();
string query = string.Format("select distinct CompanyName from CompanyTable where CompanyName like '%{0}%'", term);
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
CompanyName.Add(reader["CompanyName"].ToString());
}
}
}
return Json(CompanyName, JsonRequestBehavior.AllowGet);
}
this is the Index view:
<body>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-ui-1.8.24.js"></script>
<script>
$(function () {
$("#CompanyName").autocomplete({
source: function (request, response) {
var param = { companyName: $('#CompanyName').val() };
$.ajax({
url: '#Url.Action("Autocomplete", "Home")',
data: JSON.stringify(param),
datatype: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var err = eval("(" + XMLHttpRequest.responseText + ")");
alert(err.Message)
console.log("Ajax Error!");
}
});
},
minLength: 2 //min legth of textbox input
});
});
</script>
...later on in the same view I have the html helper textbox CompanyName.
#Html.TextBox("CompanyName", null, new { #class = "indexTextbox" })
I haven't tried re-creating this problem on my end.
Have you used your browser's code inspector to see if any errors are returned?
Also you may try placing the jquery code inside a $(document).ready() function to see if that helps.
It all looks good below I have provided the 3 parts the service works fine if queried.
/// <summary>
/// Summary description for AutoCompleteService
/// </summary>
[WebService(Namespace = "http://schemas")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class AutoCompleteService : BaseWebService
{
/// <summary>
/// Gets or sets the account finder service.
/// </summary>
public ICheckoutService CheckOutService { get; set; }
/// <summary>
/// Finds all addresses matching either the postcode or suburb given in the prefix text.
/// </summary>
/// <param name="prefixText">The prefix text.</param>
/// <param name="count">The count.</param>
/// <returns>Aray of address details</returns>
[WebMethod]
public string[] FindAddresses(string prefixText, int count)
{
//Check the parameters
if (count == 0) count = 10;
var suburbs = CheckOutService.FindMatchingForPartialAddress(prefixText);
return suburbs.Take(count).ToArray();
}
}
Followed by javascript
<script language="javascript">
$(function () {
$("#postcode").autocomplete({
source: "AutoCompleteService.asmx/FindAddresses",
minLength: 1,
select: function (event, ui) {
$(this).val(ui.item.value);
}
});
});
</script>
Followed by textbox
<asp:TextBox runat="server" name="postcode" id="postcode" ></asp:TextBox>
Response
<ArrayOfStringxmlns: xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns: xsd="http://www.w3.org/2001/XMLSchema"xmlns="http://schemas.forcetechnology.com.au/2009/04/Fulfilment"><string>ABBARIVER,WA,6280</string><string>ABBEY,WA,6280</string><string>ACTONPARK,WA,6280</string>string>ADAMSVALE,WA,6375</string></ArrayOfString>
OKay I made the following alterations thankyou all for pointing me in the right direction and also providing me with a starting point, also for this gives me error messages which helps so the revised is below.
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] FindAddresses(string prefixText)
{
//Check the parameters
var suburbs = CheckOutService.FindMatchingForPartialAddress(prefixText);
return suburbs.ToArray();
}
$(document).ready(function () {
$('[ID$=postcode]').live('keyup.autocomplete', function () {
$(this).autocomplete({
source: function (request, response) {
alert(request.term);
$.ajax({
url: '<%=ResolveUrl("AutoCompleteService.asmx/FindAddresses") %>',
data: "{ prefixText:'" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
},
minLength: 1
});
});
});
If the autocomplete is JQueryUI and you wish to provide some custom parameters to the autocomplete then you will need to provide a function to set the source. Have a look here
this should help you to define it.
Also as #Shadow-Wizzard said you may want to make sure that you have the right id's
try the following code. that is working for me..
$(document).ready(function () {
$('[ID$=txtLastname]').live('keyup.autocomplete', function () {
$(this).autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Resources/WebService.asmx/LastName") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
},
minLength: 1
});
});
Web method is
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] LastName(string prefix)
{
List<string> customers = new List<string>();
using (SqlConnection conn = new SqlConnection())
{
string connectionstring = CCMMUtility.GetCacheForWholeApplication();
conn.ConnectionString = connectionstring;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select distinct top(10) Lastname from tblusers where " +
"Lastname like '%'+ #SearchText + '%' order by Lastname";
cmd.Parameters.AddWithValue("#SearchText", prefix);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(string.Format("{0}", sdr["Lastname"]));
}
}
conn.Close();
}
return customers.ToArray();
}
}
I am working on a project that requires to autocomplete textbox when some data is inputted and the data will be fetched from a database.
For this I created a webservice as -
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[ScriptService]
public class SearchIssues : System.Web.Services.WebService
{
//[ScriptMethod]
[WebMethod]
public string[] GetCompletionList(string prefixText)
{
DataSet ds = null;
DataTable dt = null;
OracleConnection conn = null;
StringBuilder sb = new StringBuilder();
try
{
conn = new OracleConnection(WebConfigurationManager.ConnectionStrings["Conn"].ToString());
sb.Append("select issueno from cet_sepcet where issueno like '");
sb.Append(prefixText);
sb.Append("%'");
OracleDataAdapter daRes = new OracleDataAdapter(sb.ToString(), conn);
ds = new DataSet();
daRes.Fill(ds);
dt = ds.Tables[0];
}
catch (Exception exc)
{
}
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
List<string> IssueList = new List<string>();
for (int i = 0; i < dt.DataSet.Tables[0].Rows.Count; i++)
{
IssueList.Add(dt.DataSet.Tables[0].Rows[i][0].ToString());
}
return IssueList.ToArray();
}
}
The jquery ajax method I wrote is as -
$(function() {
$(".tb").autocomplete({
source: function(request, response) {
debugger;
$.ajax({
url: "SearchIssues.asmx/GetCompletionList",
data: request.term,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item
}
}))
//alert('Hello');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
debugger;
alert(errorThrown);
}
});
},
minLength: 1
});
});
The webservice is running perfectly fine. But the problem comes when I try to call the webservice from the .aspx page. Its throws Internal server error.
I am not sure as where I am going wrong. Kindly help.
Thanks in advance.
Akhil
I advice you to use firebug to check whether your Post requests and responses this way you can easily debug your application.
This one in your code of ajax
data: request.term,
Should be actually
data: "{'prefixText':'" + request.term+ "'}",
Your service is expecting prefixText string as a parmeter, I assume request.term is the value.
Update :
I dont know what is not working at your end this works for me :
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.8.custom.min.js" type="text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
$(document).ready(function() {
$("input#autocomplete").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Service/WSDataService.asmx/GetStatesWithAbbr",
data: "{'name':'" + $(autocomplete).val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.Name,
value: item.Name
}
}))
}
});
},
minLength: 1
});
});
</script>
....
<input id="autocomplete" />
Service :
[WebMethod]
public List<State> GetStatesWithAbbr(string name)
{
List<State> sbStates = new List<State>();
//Add states to the List
}
This code could throw exception, so please verify it one more time, probably table is not retrieved or something like it.
List<string> IssueList = new List<string>();
for (int i = 0; i < dt.DataSet.Tables[0].Rows.Count; i++)
{
IssueList.Add(dt.DataSet.Tables[0].Rows[i][0].ToString());
}
return IssueList.ToArray();
Place this line in your ajax:
data: '{ "prefixText": "' + request.term + '"}',
and it will work exactly as happened with me.