My JQueryAutocomplete won' work in asp net webForm - javascript

i get a little probleme that my JQuery doesn't show me a list of Autocomplete
i get a Form that show for the Client a the contrat that he have just by passing like the First Number of Contrat or middle
My JQuery
$(document).ready(function() {
SearchText();
});
function SearchText() {
$("#txtEmpName").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetEmployeeName",
data: "{'empName':'" + document.getElementById('txtEmpName').value + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("No Match");
}
});
}
});
}
</script>
My Asp net
[WebMethod]
public static List<string> GetEmp(string empdetails)
{
string id_client = HttpContext.Current.Session["id_client"].ToString();
List<string> emp = new List<string>();
string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
string sqlquery = string.Format("select Num_contrat from [dbo].[Contrat] where Num_contrat LIKE '%'"+empdetails+"'%' and ClientNum_Client= '" + id_client + "' ", empdetails);
SqlCommand sqlcomm = new SqlCommand(sqlquery, con);
SqlDataReader sdr = sqlcomm.ExecuteReader();
while(sdr.Read())
{
emp.Add(sdr.GetString(0));
}
con.Close();
return emp;
}
AspNet
<asp:Button ID="Button1" runat="server" Text="Pas de Contrat" class="btn btn-dark mb-2 btn-sm" OnClientClick="javascript:return ShowHideDivOnButtonClick();" />

if txtEmpName is a asp.net webform control than at runtime this will get renamed to a unique name. The good thing is you can get that name by doing <% txtEmpName.ClientID %>
Change your code so the field references as those and all should work.

Related

Adding two values to ajax autocomplete function in Asp.net web forms

I have search textbox and i whould like to implement autocomplete checking in it. When you type one letter autocomplete need to give you all the names with that letter.
I found tutorial with that but my problem is what I whould like implement two radio buttons and if first one is checked it will give you only suggestion for Clients, and if second one is checked it will give you only suggestion for companies.
I thried with this code in Web service .asmx
[WebMethod]
public class Autocomplete : System.Web.Services.WebService
{
[WebMethod]
public List<string> GetClientNames(string searchTerm,string rbtnValue)
{
List<string> clientNames = new List<string>();
string connStr = ConfigurationManager.ConnectionStrings["RheosConnString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr))
{
if (rbtnValue == "radio0")
{
SqlCommand cmd = new SqlCommand("spGetClientNames", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter("#term", searchTerm);
cmd.Parameters.Add(param);
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
clientNames.Add(sdr["ime"].ToString());
}
}
else
{
SqlCommand cmd = new SqlCommand("spGetCompanyNames", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter("#term", searchTerm);
cmd.Parameters.Add(param);
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
clientNames.Add(sdr["naziv"].ToString());
}
}
}
return clientNames;
}
}
My Javascript looks like this
<script type="text/javascript" language="javascript">
$(function () {
$('#<%=txtSearch.ClientID%>').autocomplete({
source: function (request, response) {
var value = $("form input[type='radio']:checked").val();
$.ajax({
url: "Autocomplete.asmx/GetStudentNames",
data: {searchTerm: request.term, rbtnValue:value},
type: "POST",
dataType: "json",
contentType: "application/json;charset=utf-8",
success: function (data) {
response(data.d);
},
error: function (result) {
alert('Postoji problem s dohvaćanjem zahtjeva');
}
});
},
minLength: 0
});
});
</script>
Do I need implement something else for radiobuttons. My value is radio0 and radio1.
Thank you!
In you service the method name is GetClientNames but in your ajax call you are calling to method GetStudentNames. Most probably this could be the issue. If this is not the issue kindly share your error so I would be able to help you out.

Record is Not updated ASP.NET Ajax

I tried to update the data but it didn't update. Data is loaded into a datatable with edit and delete buttons, when I click edit button data will be passed in to the relevant textboxes for edit. I attached the screenshot below for easy to understand the problem. If I change the data and click the button data is not updated. Add and edit both things I do at one button.
Screenshot:
Edit button in the datatable code
"sTitle": "Edit",
"mData": "id",
"render": function (mData, type, row, meta) {
return '<button class="btn btn-xs btn-success"
onclick="get_category_details(' + mData + ') ">Edit</button>';
When I click the edit button it goes to the function get_category_details(id) along with record id and displayed records on relevant textboxes
function get_category_details(id) {
$.ajax({
type: 'POST',
url: 'edit_return.asmx/doSome',
dataType: 'JSON',
data: "{id: '" + id + "'}",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
$("html, body").animate({ scrollTop: 0 }, "slow");
isNew = false;
id = data.d[0].id
$('#fname').attr('value', data.d[0].fname);
$('#age').attr('value', data.d[0].age);
}
});
}
After I make changes and click the button, it is goes to Addproject() function
this is button. else part for record updated. This how I sent the record to update.aspx page I have two fields fname and age in the form with id means
id = data.d[0].id
This I send it
{fname: '" + $('#fname').val() + "',age: '" + $('#age').val() + "'}" + "&id=" + id,
look like this way any problem on that
<input type="button" id="b1" value="add" class="form-control" onclick="addProject()" />
Addproject() function
var isNew == true// if isNew == true means the record is new
if it is false mean update one existing record
function Addproject()
{
if (isNew == true) {
_url = 'insert.aspx/doSomething';
_data = "{fname: '" + $('#fname').val() + "',age: '" + $('#age').val() + "'}";
_method = 'POST';
}
else {
_url = 'update.aspx/doSomething',
_data = "{fname: '" + $('#fname').val() + "',age: '" + $('#age').val() + "'}" + "&id=" + id,
_method = 'POST';
}
$.ajax({
type: _method,
url: _url,
dataType: 'JSON',
contentType: "application/json; charset=utf-8",
data: _data,
success: function (data) {
// alert("success");
get_all();
var msg;
if (isNew = true)
{
alert("Data Added");
}
else
{
alert("Data Updated");
}
});
}
}
This is code for receiving the data and update the record at update.aspx
update.aspx
public class UserClass
{
public string fname { get; set; }
public int age { get; set; }
}
[WebMethod]
public static string doSomething(string fname, int age, int id)
{
SqlConnection con = new SqlConnection("server=.; Initial Catalog = jds; Integrated Security= true;");
string sql = "update record set name ='" + fname + "', age ='" + age + "' where id = '" + id + "')";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return "Success";
}

AJAX POST to WEB Method not working for me

I coded up just like everybody else on the net but my WebMethod isn't getting hit from the post action. I believe my code is fine but I'll post my code just in case.
I put a breakpoint in the WebMethod, this is how I know it isn't being called.
Any help would be appreciated.
AXAJ
var div = document.getElementById(this.id);
var divid = div.getElementsByClassName("portlet-id");
varSQL="UPDATE [ToDoTrack] SET [Status] = '" + this.id + "' WHERE [ID] = '" + divid[0].innerHTML + "'";
var item = {};
item.status = this.id;
item.id = divid[0].innerHTML;
var Data = '{varSQL: ' + varSQL + ' }'
$.ajax({
type: "POST",
url: "ToDoTrack.aspx/UpdateDB",
data: Data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
window.location.reload();
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert("Status: " + textStatus);
alert("Error: " + errorThrown);
}
});
Code Behind
[WebMethod]
[ScriptMethod]
public static void UpdateDB(string varSQL)
{
string connStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(varSQL))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
There is a problem the data object, it's a string not an object
Its not recommended to create the SQL on client side, it's a security flaw unless it's an application
//Problem is a string not object
var Data = '{varSQL: ' + varSQL + ' }'
//Solution below
var Data = {'varSQL': varSQL };
// Or this
var Data = 'varSQL='+varSQL;
The code seemed to work fine but if you have this issue in the future, these are the things I got from the internet that you seem to need for ajax post to work with WebMethods:
Ensure your URL in AJAX is correct
Ensure your json is well formed
Set <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">, my script manager was in my site.master
Set settings.AutoRedirectMode = RedirectMode.Off; in the App_Start>RouteConfig.cs file

Filling GridView in javascript is not working and no error catched

ok I am trying to fill an asp GridView using javascript. The webService call has succeeded and I can retrieve data normally. But when I want to display it in my Grid nothing happens.
Javascript Functions:
function SearchUsers() {
AutoComplete.ShowLoginUserOnSearch("PL", "pi", "", "", "", 0, 20, onGetLoginUserSuccess);
}
function onGetLoginUserSuccess(result) {
alert(result[1].ProviderName);
$("#grdvUserInfo").append("<tr><td>" + result[1].UserName +
"</td><td>" + result[1].ProviderName + "</td></tr>");
alert(result[1].UserName);
}
Asp.net:
<asp:GridView ID="grdvUserInfo" AllowPaging="True" PagerSettings-
Mode="NextPreviousFirstLast" PageSize="20" runat="server"
AutoGenerateColumns="False" Width="700px" SkinID="grdMySite"
DataSourceID="ObjectDataSource1">
</asp:GridView>
Both alerts are filled with the correct data, what could be the problem?
HTML
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">script>
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetCustomers",
data: '{}',
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 customers = xml.find("Table");
var row = $("[id*=gvCustomers] tr:last-child").clone(true);
$("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
$.each(customers, function () {
var customer = $(this);
$("td", row).eq(0).html($(this).find("CustomerID").text());
$("td", row).eq(1).html($(this).find("ContactName").text());
$("td", row).eq(2).html($(this).find("City").text());
$("[id*=gvCustomers]").append(row);
row = $("[id*=gvCustomers] tr:last-child").clone(true);
});
}
<script>
Web Method
[WebMethod]
public static string GetCustomers()
{
string query = "SELECT top 10 CustomerID, ContactName, City FROM Customers";
SqlCommand cmd = new SqlCommand(query);
return GetData(cmd).GetXml();
}
private static DataSet GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["conString"].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);
return ds;
}
}
}
}
http://www.aspsnippets.com/Articles/Populate-ASPNet-GridView-by-binding-DataSet-Client-Side-using-jQuery-AJAX.aspx
Asp.net
<asp:GridView ID="grdvUserInfo" AllowPaging="True" PagerSettings-
Mode="NextPreviousFirstLast" PageSize="20" runat="server"
AutoGenerateColumns="False" Width="700px" SkinID="grdMySite"
DataSourceID="ObjectDataSource1">
</asp:GridView>
Function
function onGetLoginUserSuccess(result) {
alert(result[1].ProviderName);
$("#grdvUserInfo").append("<asp:TemplateField><ItemTemplate>" + result[1].UserName +
"</ItemTemplate></asp:TemplateField><asp:TemplateField><ItemTemplate>" + result[1].ProviderName +
"</ItemTemplate></asp:TemplateField>");
alert(result[1].UserName);
}

JQuery autocomplete with using handler

I' m trying to create a search box with autocomplete property and using a handler.
I got all words from database but can not show them.
It' s jquery part:
$(function () {
$("#search-box").autocomplete({
source: "KeywordHandler.ashx",
minLength: 1,
#*select: function (event, ui) {
alert(ui.item.id + " / " + ui.item.value);
}*#
});
});
It' s handler part:
public class KeywordHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string prefixText = context.Request.QueryString["term"];
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["DSN"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Keyword from [dbo].[Log] where " + "Keyword like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
StringBuilder sb = new StringBuilder();
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
sb.Append(sdr["Keyword"])
.Append(Environment.NewLine);
}
}
conn.Close();
context.Response.Write(sb.ToString());
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
At handler, I can get all the words which I need but can not show them as offered keywords at search box.
Is there any idea?
You may use something like below. Pay attention to "refresh" part. You should return your query result as JSON from webservice and then parse it. After parse, you can create list item for every search result item as I indicated in JQuery code (the last part of the code).
*I wrote my answer as supposing you are getting the result from your service properly.
HTML
<div id="assignDiv" style="display:none;">
<div data-demo-html="true" data-demo-js="true" data-demo-css="true">
<h3>Select contact:</h3>
<ul id="autocomplete" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="Search contact..." data-filter-theme="d"></ul>
</div>
<input type="button" value="Send to selected contact" id="assignToBtn" />
</div>
JQuery
$("#autocomplete").on("listviewbeforefilter", function (e, data) {
var $ul = $(this),
$input = $(data.input),
value = $input.val(),
html = "";
$ul.html("");
if (value && value.length > 2) {
$ul.html("<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>");
$ul.listview("refresh");
$.ajax({
type: "POST",
crossDomain: true,
url: serverAddress + "General.asmx/AutoComplete",
data: "{'q': '" + $input.val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.then(function (response) {
var JsonObj = jQuery.parseJSON(response.d);
$.each(JsonObj, function (i, val) {
html += "<li><a href='javascript:changeAutoCompleteText(\"" + val + "\");'>" + val + " <i style='color:grey;font-weight:lighter;'>(</i><i style='text-decoration:underline;color:grey;font-weight:lighter;'>" + val + "</i><i style='color:grey;font-weight:lighter;'>)</i></a></li>";
});
$ul.html(html);
$ul.listview("refresh");
$ul.trigger("updatelayout");
});
}
});

Categories

Resources