How to list autocomplete results as a link? - javascript

I am new on Ajax. I need to find how to list autocomplete results as a link. When user clicks the result should open that link. I can list the related result but I couldn't find how to add the links. It should be added somewhere in the script as a html tag. Please give me some clue how to add html link
Here is my script:
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".auto").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'question':'" + document.getElementById('txtQuestion').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error Occurred");
}
});
}
});
}
</script>
Here is the method which connects to the db and returns related results:
[WebMethod]
public static List<string> GetAutoCompleteData(string question)
{
List<string> result = new List<string>();
using (SqlConnection conn = new SqlConnection("Data Source=xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx+"))
{
using (SqlCommand cmd = new SqlCommand("SELECT Questions,Link FROM DigiQA WHERE Questions LIKE '%'+#quest+'%'", conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#quest", question);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Questions"].ToString());
}
return result;
}
}
}

Try something like this
success: function(data) {
response($jQuery.map(data, function(item) {
return {
label: '' + item + ''),
value: item
}
}))
}

Related

Bootstrap.css and Vendors.min.js are creating problem for an Autocomplete Textbox in Asp.net webforms

I am facing a problem while making an autocomplete textbox in asp.net with javascript and c#
The problem is that nothing is working if I include the links to /bootstrap.css and /vendors.min.js on my page.aspx.
If I remove those then everything works fine.
I cannot remove that link and script because my full project is depending on them. Can anyone please help me to solve this?
These are the tags I've added:
<link rel="stylesheet" type="text/css" href="/app-assets/css/bootstrap.css"/>
<script src="/app-assets/vendors/js/vendors.min.js"></script>
This is my Script:-
<script type="text/javascript">
$(function() {
$("#textbox").autocomplete({
source: function(request, response) {
var param = {
name_details: $('#textbox').val()
};
$.ajax({
url: "Page.aspx/Get_Names",
data: JSON.stringify(param),
type: "post",
contentType: "application/json; charset=utf-8",
datafilter: function(data) {
return data;
},
success: function(data) {
response($.map(data.d, function(items) {
return {
value: items
}
}))
},
});
},
minLength: 1
});
});
</script>
this is my c# Code:
[WebMethod]
public static List<string> Get_Names (string name_details)
{
String Command_Query = System.Configuration.ConfigurationManager.AppSettings["SP_Product_Name_Search"].ToString();
List<string> Product_names = new List<string>();
String MasterConnection = System.Configuration.ConfigurationManager.AppSettings["Connectionstring"].ToString();
SqlConnection con = new SqlConnection(MasterConnection);
string sqlqry = string.Format(Command_Query + " '{0}'", name_details);
con.Open();
SqlCommand command = new SqlCommand(sqlqry,con);
SqlDataReader sdr = command.ExecuteReader();
while (sdr.Read())
{
Product_names.Add(sdr.GetString(0));
}
con.Close();
return Product_names;
}

C# .aspx javascript .ajax autocomplete textbox returns 500 error when run from IIS 8

Well, after a week of trying just about everything I could find on here, and elsewhere, to resolve this problem, I'm finally flying the flag of surrender and opening this up to my better experienced fellows. Basically I have a simple intranet app that resides on a VMed Windows 2012 R2/IIS8 server, which also hosts SQL 2014(I know, I know). I'm trying to autocomplete on two textboxes from a SQL table. In VS2017 it works perfectly fine, but when I try running it from IIS8 I get a "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" error.
Here's the HTML:
<script type="text/javascript">
$(function () {
$("#<%=txtSAPLoc.ClientID%>").autocomplete({
source: function (request, response) {
var param = { locName: $('#<%=txtSAPLoc.ClientID%>').val() };
$.ajax({
method: "POST",
url: "CdtCreateRecord.aspx/GetLoc",
data: JSON.stringify(param),
dataType: "json",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
},
minLength: 2
});
});
$(function () {
$("#<%=txtSAPInst.ClientID%>").autocomplete({
source: function (request, response) {
var param = { instName: $('#<%=txtSAPInst.ClientID%>').val() };
$.ajax({
method: "POST",
url: "CdtCreateRecord.aspx/GetInst",
data: JSON.stringify(param),
dataType: "json",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
},
minLength: 2
});
});
</script>
And the relevant code behind:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static List<string> GetLoc(string locName)
{
List<string> Loc = new List<string>();
string query = string.Format("SELECT DISTINCT loc FROM Locations WHERE loc LIKE '%{0}%'", locName);
using (SqlConnection con = new SqlConnection("Server=usmac2dgsyntax;Database=LREC_ADB;Trusted_Connection=Yes;"))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Loc.Add(reader.GetString(0));
}
}
}
return Loc;
}
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static List<string> GetInst(string instName)
{
List<string> Inst = new List<string>();
string query = string.Format("SELECT DISTINCT inst FROM Institutions WHERE inst LIKE '%{0}%'", instName);
using (SqlConnection con = new SqlConnection("Server=usmac2dgsyntax;Database=LREC_ADB;Trusted_Connection=Yes;"))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Inst.Add(reader.GetString(0));
}
}
}
return Inst;
}
This is a sampling of stackoverflow articles I previously consulted:
asp-net-500-internal-server-error-while-calling-webmethod-from-javascript
query-ajax-call-works-on-localhost-but-not-on-live-server
500-internal-server-error-in-asp-net
jquery-ajax-post-results-in-500-internal-server-error
In the end the, solution to my problem was maddeningly simple: After setting up remote debugging I found that a SQL authentication error was, in turn, causing the 500 internal server error. In SQL I had assumed that the NT AUTHORITY\NETWORK SERVICE account had the correct datareader/datawriter permissions on the relevant DB, but they had never been assigned, hence the authentication error and the internal server error in production. I fixed that, and it all works now. Thanks for the tips.

Autocomplete textbox don't show result inside clicking of textbox

I have a autocomplete textbox which filters exactly what I want to search for. But now what I want is,
If user doesn't types anything into the textbox and just clicks the textbox. It should show all the result. Is this possbile ?
Below is my code.
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("#txt712").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Frm_Agreement_Master.aspx/GetAutoCompleteData",
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
},
focus: function () {
return false;
},
select: function (event, ui) {
var terms = split(this.value);
terms.pop();
terms.push(ui.item.value);
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("#txt712").bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
}
Also find the link from where I got the reference.
Reference link
UPDATE
Server side code
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (OracleConnection ObjPriCon = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString()))
{
using (OracleCommand cmd = new OracleCommand("select distinct survey_area_7_12 FROM xxcus.xxacl_pn_farming_mst WHERE survey_area_7_12 LIKE '%' || :searchtext || '%'", ObjPriCon))
{
ObjPriCon.Open();
cmd.Parameters.AddWithValue(":searchtext", username.ToLower());
OracleDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
result.Add(dr["survey_area_7_12"].ToString());
}
}
return result;
}
}
}
In Server code check if the search string is null or not and trigger the query accorduingly
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
**//check if user name is not null**
if(null != username){
using (SqlCommand cmd = new SqlCommand("select DISTINCT UserName from UserInformation where UserName LIKE '%'+#SearchText+'%'", con))}
else{
using (SqlCommand cmd = new SqlCommand("select UserName from UserInformation, con))}
}
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["UserName"].ToString());
}
You can use "Focus" event to do this.
.focus(function () {
$(this).autocomplete("search");
});
Full code as below.
$("#txt712").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Frm_Agreement_Master.aspx/GetAutoCompleteData",
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
},
focus: function () {
$(this).autocomplete("search"); //New Code
},
select: function (event, ui) {
var terms = split(this.value);
terms.pop();
terms.push(ui.item.value);
terms.push("");
this.value = terms.join(", ");
return false;
}
});

JSON stringify on lists in C# web form

I use JSON.stringify for a textbox autocomplete for a web-form. What I want to do is; autocomplete a textbox for city names by getting appropriate city names from my database. Autocomplete works after 3 letters.
The problem is; suggested city names are shown in one line. For example, when I typed are to textbox (which is named "MainContent_city") it is shown like: "Arequipa,Arecibo,Are Ostersund,Arezzo,Arendal" in one line, as one string object. What I want is to show all of those city names line by line. Such as;
Arequipa
Arecibo
Are Ostersund
Arezzo
Arendal
Below is my javascript code;
<script type="text/javascript">
$(function () {
$("#MainContent_city").autocomplete({
source: function (request, response) {
var param = { cityname: $('#MainContent_city').val() };
$.ajax({
url: "HotelAdd.aspx/GetCities",
data: JSON.stringify(param, null, param.length),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
},
minLength: 3
});
});
</script>
This is my C# code for "GetCities" method
[WebMethod]
public static List<string> GetCities(string cityname)
{
List<string> City = new List<string>();
string query = "SELECT name FROM City WHERE name LIKE #SearchText + '%'";
//Note: you can configure Connection string in web.config also.
SqlCommand cmd = new SqlCommand(query, connection);
cmd.Parameters.AddWithValue("#SearchText", cityname);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds2 = new DataSet();
adapter.Fill(ds2);
for(int i=0; i<ds2.Tables[0].Rows.Count; i++)
{
City.Add(ds2.Tables[0].Rows[i][0].ToString());
}
return City;
}
Data is contained in data.d.
Change this response($.map(data, function (item) to response($.map(data.d, function (item)
success: function (data)
{
response($.map(data.d, function (item) {
return
{
value: item
}
}))
},

Autocomplete textbox in asp.net mvc4 using ajax and jQuery

I am trying to fetch company name in textbox as autocomplete. When I run my project, Ajax will call the success function, and the record is also fetched correctly, but there are no autocomplete suggestions in the textbox.
My view is:
$("#idcompanyname").autocomplete({
source: function (request, response) {
var customer = new Array();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("Companymap", "admin")',
data: "{'term':'" + document.getElementById('idcompanyname').value + "'}",
dataType: "json",
success: function (data) {
alert(data)
response($.map(data, function (v, i) {
var text = v.vcCompanyName;
alet(text)
if (text && (!request.term || matcher.test(text))) {
return {
label: v.vcCompanyName,
value: v.kCompanyId
};
}
}));
},
error: function(result) {
alert("No Match");
}
});
}
});
}
Here is Method on controller:
var query = db.tbaccounts.Where(t => t.vcCompanyName.ToLower()
.StartsWith(term)).ToList();
List<string> lst = new List<string>();
foreach (var item in query)
{
lst.Add(item.vcCompanyName);
}
return Json(lst, JsonRequestBehavior.AllowGet);
Here is the referred Javascript:
<script src="~/script/jquery-2.0.3.js"></script>
<script src="~/script/jquery-ui.js"></script>
<script src="~/js/jquery-1.10.2.js"></script>
<script src="~/js/jquery-ui.js"></script>
Please try removing
~/script/jquery-2.0.3.js
from the script references in your application, and that should work for you....

Categories

Resources