JQUery autocomplete in ASP.Net Webservice - c#

This is driving me crazy , I just keep getting the message "error" nothing else. I had this autocomplete working with AJAX Toolkit, but I want to try JQuery, I have very little experience with JQuery. Here is WebService code:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public static string GetNames(string prefixText, int count)
{
Trie ArtistTrie = new Trie();
if (HttpContext.Current.Cache["CustomersTrie"] == null)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstring"].ConnectionString);
SqlCommand comm = new SqlCommand();
comm.CommandText = "SELECT * FROM TopArtists ORDER BY name ASC";
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = comm;
comm.Connection = conn;
conn.Open();
da.Fill(dt);
conn.Close();
Trie newtrie = new Trie();
foreach (DataRow dr in dt.Rows)
{
// topartists.Add(dr[0].ToString());
newtrie.Add(dr[0].ToString());
}
HttpContext.Current.Cache["CustomersTrie"] = newtrie;
}
ArtistTrie = (Trie)HttpContext.Current.Cache["CustomersTrie"];
List<string> list = ArtistTrie.GetCompletionList(prefixText, 10);
List<Band> list1 = new List<Band>();
foreach (string a in list)
{
Band newband = new Band();
newband.Name = a;
list1.Add(newband);
}
string json = JsonConvert.SerializeObject(list1, Formatting.Indented);
return json;
}
Here is JQuery Code:
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$("#tb1").autocomplete({
source: function (request, response) {
$.ajax({
url: "WebService.asmx/GetNames",
data: request.term ,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
})
</script>

Well for one, your jQuery code has errors, including a missing semicolon at the end and an unnecessary function wrapping the autocomplete, try:
<script type="text/javascript">
$(document).ready(function() {
$("#tb1").autocomplete({
source: function(request, response) {
$.ajax({
url: "WebService.asmx/GetNames",
data: request.term,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
</script>

for the ajax part, the return need to be in array, string[]
sample code,
[WebMethod]
public string[] area(string prefixText)
{
List<string> listString = new List<string>();
using (SqlConnection con = new SqlConnection("Initial Catalog=EMS;Server=S-CEMSDB01;User ID=sa;Password=sqltest"))
{
SqlCommand cm = new SqlCommand("select distinct eqp_location from EQUIPMENT where eqp_location like '" + prefixText + "%' order by eqp_location", con);
con.Open();
SqlDataReader dr = cm.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
listString.Add((dr["eqp_location"].ToString()));
//c.FullName, serializer.Serialize(c))
}
}
dr.Close();
dr.Dispose();
con.Close();
}
string[] str = listString.ToArray();
return str;
}

Related

SyntaxError: Unexpected token < in JSON at position 4 in ajax call in asp.net

I am binding data on dropdown index change event using ajax call using asp.net web form
following my Ajax code
var e = document.getElementById("<%=ddlEducation.ClientID%>");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
if (value == "0") {
$('#dvRecords').empty();
alert("Please Select Education");
return false;
}
var obj = { "iEduid": value};
var myJSON = JSON.stringify(obj);
//Filling Grid View
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'EditProfile.aspx/BINDEducationDATA',
data: myJSON,
dataType: 'JSON',
success: function (response) {
document.getElementById("ctl00_ContentPlaceHolder2_lblstram").value = response.d[i].eduStream
document.getElementById("ctl00_ContentPlaceHolder2_lbldescs").value = response.d[i].Edu_Description
},
error: function (xhr, status, error) {
console.log(xhr);
alert(status);
alert(error);
}
});
when it it executing i am getting 1st error is parsererror next i am getting error saying Unexpected token < in JSON at position 4.
above is my C# code
[WebMethod]
public static List<EduDesc> BINDEducationDATA(string iEduid)
{
List<EduDesc> details = new List<EduDesc>();
DataTable dtManager = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
cmd = new SqlCommand("Select Edu_Stream,Edu_Description from tbl_education WHERE ID='" + iEduid + "'", con);
da.SelectCommand = cmd;
da.Fill(dtManager);
}
foreach (DataRow dtrow in dtManager.Rows)
{
EduDesc logs = new EduDesc();
logs.Edu_desc = (dtrow["Edu_Description"].ToString());
logs.eduStream = dtrow["Edu_Stream"].ToString();
details.Add(logs);
}
return details;
}
any help will appreciated.
There are a couple areas of concern.
foreach (DataRow dtrow in dtManager.Rows)
{
EduDesc logs = new EduDesc();
// - extra parentheses.
// - here you use logs.Edu_desc but in 'success' (below) you use Edu_Description.
logs.Edu_desc = (dtrow["Edu_Description"].ToString());
logs.eduStream = dtrow["Edu_Stream"].ToString();
details.Add(logs);
}
success: function (response) {
// here you're looking for [i], but what is i? you need an integer.
document.getElementById("ctl00_ContentPlaceHolder2_lblstram").value =
response.d[i].eduStream
document.getElementById("ctl00_ContentPlaceHolder2_lbldescs").value =
response.d[i].Edu_Description
},
In the success function, do a console.log(d) to double-check the results.
hth.

Failed to load WebMethod

My drop down change function works good. But the WebMethod failed to load
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("[id*=drpSub]").change(function () {
var drpSub = $("[id*=drpSub]").val();
var Gs_Id = $("[id*=ddlClass]").val();
alert(drpSub);
$.ajax({
type: 'GET',
url: 'assignments1.aspx/GetAssignmentType',
data: {},
dataType: 'json',
success: function (r) {
//var ddlCustomers = $("[id*=drpType]");
//ddlCustomers.empty().append('<option selected="selected" value="0">Please select</option>');
//$.each(r.d, function () {
// ddlCustomers.append($("<option></option>").val(this['Value']).html(this['Text']));
//});
}
});
});
});
Code Behind
[WebMethod]
public static List<ListItem> GetAssignmentType()
{
string query = "SELECT OP_AssignmentType.AT_Id, OP_AssignmentType.AT_Type + ' (' + CONVERT(varchar(10), COUNT(8)) + ')' AS AT_Type FROM OP_Assignments INNER JOIN OP_AssignmentType ON OP_Assignments.OP_AS_TypeId = OP_AssignmentType.AT_Id WHERE (OP_Assignments.OP_AS_SubjId = '" + 10 + "') AND (OP_Assignments.OP_GS_IdNo = 37) And OP_AS_LastDate>='" + DateTime.Now + "' GROUP BY OP_AssignmentType.AT_Id, OP_AssignmentType.AT_Type";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
List<ListItem> customers = new List<ListItem>();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new ListItem
{
Value = sdr["Sub_Id"].ToString(),
Text = sdr["Subject_Name"].ToString()
});
}
}
con.Close();
return customers;
}
}
}
I know code inside the web method may be wrong. My actual problem is, the page is not loading when in put break point in the web method code behind. My console is error free. Is their any fault in my jQuery. Please Help
You have to add contentType: "application/json; charset=utf-8", in your ajax so, your ajax would be like
$.ajax({
type: 'GET',
url: 'Default.aspx/GetAssignmentType',
data: {},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (r) {
//var ddlCustomers = $("[id*=drpType]");
//ddlCustomers.empty().append('<option selected="selected" value="0">Please select</option>');
//$.each(r.d, function () {
// ddlCustomers.append($("<option></option>").val(this['Value']).html(this['Text']));
//});
}
});

Auto Suggestion Search Box in master page not working

I'm attempting to implement an autocomplete search feature in the master page of my project to be used by other pages inheriting the master page but the function returns an error despite there being data in my database table to return. I have checked that the table name, textbox ID and column is correct but I'm still not sure what the problem is. Any help would be appreciated!
This is the script in my master page file:
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$("#searchTerm").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AutoCompleteService.asmx/GetmovieTitle",
data: "{'name':'" + document.getElementById('searchTerm').value + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("No Match");
}
});
}
});
}
</script>
This is the content of my webservice page:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoCompleteService : System.Web.Services.WebService
{
[WebMethod]
public List<string> GetmovieTitle(string name)
{
List<string> mResult = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\QACinema\\QACinema\\App_Data\\QACinemaHomeCopy.mdf';Integrated Security=True;User Instance=True"))
{
using (SqlCommand cmd = new SqlCommand())
{
con.Open();
cmd.CommandText = "Select name from movies where name LIKE '+#name+'%'";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#name", name);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
mResult.Add(dr["name"].ToString());
}
return mResult;
}
}
}
}

Textbox Change Event not working

I have two Textboxes,I'm trying to fill the Second Textbox at change Event of Textbox1
Eg:
I have to fill the Customer Name when i type the Customer Code at TextBox1.
MY Script:
$(document).ready(function() {
userCodeChangeEvent();
});
function userCodeChangeEvent() {
$('#<%=txtCustomerCode.ClientID %>').change(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Customer_Bill.aspx/GetNameByCode",
data: "{'CusName':'" + document.getElementById('<%=txtCustomerCode.ClientID %>').value + "'}",
dataType: "json",
success: function(data) {
$('#<%=txtcustomerName.ClientID %>').value = data.d;
},
error: function(result) {
alert("No Match");
}
});
});
}
C#:
[WebMethod]
public static string GetNameByCode(string CusName)
{
// List<string> empResult = new List<string>();
string empResult = "";
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Constring"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select user_name From tbl_member_Registration where user_code=#SearchEmpName";
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("#SearchEmpName", CusName);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
empResult=dr["user_name"].ToString();
}
con.Close();
return empResult;
}
}
}
but it doesn't working .How do i Solve this?
In client side 2 things you should notice :
1- $(...).val(data.d);
2- use "keyup" instead "change" because change will not be fired while the user is typing.
In Server side make sure that you enabled "ScriptService" by adding the [System.Web.Script.Services.ScriptService] attribute to the web service class (code behind the asmx) as the following:
[System.Web.Script.Services.ScriptService]
public class WS : System.Web.Services.WebService
{
[WebMethod]
public static string GetNameByCode(string CusName)
{
...
}
}
In your success function use val() instead of val= like this
success: function(data) {
$('#<%=txtcustomerName.ClientID %>').val(data.d);
}
,
And if necessary change this line also
data: "{'CusName':'" + $('#<%=txtCustomerCode.ClientID %>').val() + "'}",

I want to fetch some data from database on click of the link using jquery but on clicking link getting an alert with undefined type

I want to get data from the database based on the text of that link on click of the link but getting undefined alert message.
I'm new to jquery so please help me out with this if anybody can. Thanks in advance.
here is the code snippet
jquery
<script type="text/javascript">
var name;
$(function () {
$("[id*=Menu] td a").click(function () {
name=$(this).text().trim();
GetRecords();
//alert(name);
});
});
function GetRecords() {
$("#loader").show();
$.ajax({
type: "POST",
url: "kioskstore.aspx/GetPrice",
data: '{name: ' + name + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var productsInfo = xml.find("Products_Info");
productsInfo.each(function () {
var customer = $(this);
$(".price").html(customer.find("Products_Price").text().trim());
});
$("#loader").hide();
}
</script>
asp.net
<div style="margin-top:25px;height:40px;float: left;margin-left:40px;font-family:cursive;font-size:24px;color:#ffe476;">
<asp:Label runat="server" CssClass="price" Text=""></asp:Label>
</div>
and the code behind C#
[WebMethod]
public static string GetPrice(string name)
{
return GetPriceData(name).GetXml();
}
public static DataSet GetPriceData(string name)
{
string query = "select * from Product_Info where Product_Name=#pname";
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#pname", name);
//cmd.Parameters.Add("#PageCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
return GetData(cmd);
}
private static DataSet GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["mycon"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds, "Product_Info");
return ds;
}
}
}
}
I think you are missing enclosing quotes for string.
Use
data: '{name: "' + name + '"}'
instead of
data: '{name: ' + name + '}'
Responding to your comment:
That message means you are requesting an incorrect URL. Please try with this.
url:document.location + '/GetPrice'
Please confirm whether your request is going to the correct URL. You can use the network monitor component of a browser development tools or an HTTP proxy like Fiddler. If you have chrome, you can check this using the Network tab of the Development Tools. Additionally you can make use of a chrome plugin called Postman to invoke HTTP request to check if they are working or not.
if you are calling from the same page?

Categories

Resources