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']));
//});
}
});
Related
I am using https://selectize.github.io/selectize.js/
and I've followed their example for dynamic population
in my aspx page I have
$('#stationid').selectize({
valueField: 'value',
labelField: 'text',
searchField: ['text'],
create: function (input, callback) {
$.ajax({
url: 'Search.aspx/GetListboxValues',
data: "{'query':'" + input+ "'}",
type: 'POST',
dataType: 'json',
success: function (response) {
return callback(response);
}
});
},
render: {
option: function (item, escape) {
return '<div>' + escape(item.text) + '</div>';
}
},
load: function (query, callback) {
if (!query.length) return callback();
$.ajax({
type: "POST",
url: "Search.aspx/GetListboxValues",
data: "{'query':'" + query + "'}",
contentType: "application/json; charset=utf-8",
dataType: 'json',
error: function () {
callback();
},
success: function (res) {
callback(res);
}
});
}
});
<asp:ListBox ID="stationid" Width="300" SelectionMode="Multiple" runat="server">
</asp:ListBox>
In my aspx.cs I have
[WebMethod]
public static string GetListboxValues(string query)
{
string _conString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(_conString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
string sql = "select station_name as [value], station_name as [text] from station where station_name like '%" + query + "%' group by station_name order by station_name asc";
cmd.CommandText = sql;
con.Open();
DataTable dt = new DataTable();
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
return JsonConvert.SerializeObject(dt);
}
The webmethod works and returns a json in the following format
{"d":"[{\"value\":\"I-M-987\",\"text\":\"I-M-987\"},{\"value\":\"S-2987\",\"text\":\"S-2987\"},{\"value\":\"S-987\",\"text\":\"S-987\"}]"}
If I type in the listbox then selectize adds what I'm typing and fires off the webmethod but the listbox is not populating with the returned json values. How can I solve this ? Thank you in advance!
in case anyone else has this issue, the freaking problem was the json was formatted wrong.
I needed to use eval function to get only text from json, because raw json had all those \"
so just do this
success: function (res) {
var rspns = eval(res.d);
callback(rspns);
}
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 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?
I cannot seem to figure out what is wrong with the code for the autocomplete search bar.
The only thing I can think of is that I referenced the wrong thing under URL
aspx Javascript
$(document).ready(function() {
SearchText();
});
function SearchText() {
$(".ui-autocomplete").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Admin_home.aspx/GetAutoCompleteData",
data: "{'Car':'" + document.getElementById('query').value + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
Error: function(results) {
alert("Error");
}
});
}
});
}
</script>`
aspx html code
I cant seem to type or paste the html here. It is just a
asp:Textbox ID="query" class="ui.autocomplete"
c# code
[WebMethod]
public static List<string> GetAutoCompleteData(string Car)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CarsConnectionString"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT Car from T_Car where Car like '%'+ #SearchText +'%", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", Car);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Car"].ToString());
}
return result;
}
}
}
Would part of the html need to be wrapped in an AJAX update panel?
Also, I am having the search pull names from sql server 2005.
that is not how jQuery Autocomplete works,
jQuery autocomplete automatically sends the text entered in the text box to the location you specify in a querystring "term" you access it in webmethod or handler like this
string input = HttpContext.Current.Request.QueryString["term"];
something like this
[WebMethod]
public static List<string> GetAutoCompleteData(string Car)
{
string input = HttpContext.Current.Request.QueryString["term"];
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CarsConnectionString"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT Car from T_Car where Car like '%'+ #SearchText +'%", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", input);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Car"].ToString());
}
return result;
}
}
}
this goes in your .aspx page
$(".ui-autocomplete").autocomplete({
source: "Admin_home.aspx/GetAutoCompleteData",
select: function (event, ui) { }
});
EDIT:
I've never actually done this in web method , I usually use a handler .ashx , but this should work just as good.
when you have all that changed , then run the site in debug mode, start to type in the textbox and fit f12 and watch the traffic that this is causing - if you type "abc" it should look like
Admin_home.aspx/GetAutoCompleteData?term=abc
then the response you might have to play with a little , by default .net is going to add "d : ...." to the response to client side , but you can watch it and adjust accordinly
Another Edit:
<asp:Textbox ID="query" class="ui.autocomplete">
is not what you put in the jquery
$(".ui-autocomplete").autocomplete({
it should be
<asp:Textbox ID="query" class="ui-autocomplete">
Yet, Another Edit:
This is missing a single quote
using (SqlCommand cmd = new SqlCommand("select DISTINCT Car from T_Car where Car like '%'+ #SearchText +'%", con))
replace with
using (SqlCommand cmd = new SqlCommand("select DISTINCT Car from T_Car where Car like '%'+ #SearchText +'%' ", con))
try this maybe it would help
<script type="text/javascript">
$(function() {
$(".ui-autocomplete").autocomplete({
source: function(request, response) {
$.ajax({
url: "Admin_home.aspx/GetAutoCompleteData",
data: "{ 'Car': '" + 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
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
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;
}