JQuery autocomplete with using handler - javascript

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");
});
}
});

Related

My JQueryAutocomplete won' work in asp net webForm

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.

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

How decode html content bound in json?

I am using asp.net application and using ajax call,below is my code.Below is my web method which is working fine and give response of ajax call.
ADController adc = new ADController();
DataTable dt = adc.GetGeneral(Convert.ToInt32( AnnouncementId));// GetAnnouncementsByIDAndRead(Convert.ToInt32(AnnouncementId), Convert.ToInt32(userid));
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
Dictionary<string, object> childRow;
foreach (DataRow row in dt.Rows)
{
childRow = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
if (col.ColumnName == "description")
{
childRow.Add(col.ColumnName, HttpUtility.HtmlDecode( Convert.ToString( row[col]) )as object);
}
else
childRow.Add(col.ColumnName, row[col]);
}
parentRow.Add(childRow);
}
return jsSerializer.Serialize(parentRow);
following is my ajax code ,which is working fine and giving data on call fine.
function fnshowAncDetails(AnnouncementId, userid) {
$(".loading").show();
var url = $("[id$='hdURLt']").val();
$("[id$='btnSaveMD']").show();
$.ajax({
type: "POST",
url: url + "/GetInfo.aspx/General",
data: '{AnnouncementId:"' + AnnouncementId + '",userid:"' + userid + '"}',
contentType: "application/json; charset=utf-8",
//dataType: "json",
success: OnSuccessSetCGiven,
error: function (response) {
}
});
var vtext = $("[id$='lblAnnoucement']").text();
if (vtext != 0) {
vtext = vtext - 1;
}
$("[id$='lblAnnoucement']").text(vtext);
}
below is my success method
function OnSuccessSetCGiven(response) {
var parsed = $.parseJSON(response.d);
$("[id$='htititlen']").text(parsed[0].Title);
$("[id$='divNotifBody']").text(parsed[0].Description);
$("[id$='divadded']").text("By:"+parsed[0].FirstName + " " + parsed[0].LastName);
$("#divNotifdetails").modal('show');
$(".modal-backdrop").css('z-index', '0');
$(".loading").hide();
var formattedTime = parsed[0].stime.Hours + ":" + parsed[0].stime.Minutes;
//$("[id$='divtime']").text(formattedTime);
$("[id$='divdate']").text("Time:" +parsed[0].startdate + " " + formattedTime);
}
Now my question is in The Description there may be html tags, means formatted htmls,like <p>xxx</p><b>sdf</b>. So it not loaded as bold,
how can I render formatted html?
Use jQuery .html function and not .text:
function OnSuccessSetCGiven(response) {
...
$("[id$='divNotifBody']").html(parsed[0].Description);
...
}
But note that you will have JS injection vulnerability, so you must clean the HTML code in the description field and remove unwanted attributes & tags (for example: <script>, <any onclick=""> etc.)
Update:
By the way, I am not familiar with this selection syntax:
$("[id$='divNotifBody']")
Assuming that you want to select a div with the id "divNotifBody", Why not just use:
$("#divNotifBody")

ul tag Binding Error using jquery

I am working on an asp.net application where i have to an ul tag. Here is my design view
<ul class="products_list" id="ulProductCart">
<li>
<div class="clearfix">
<img class="f_left m_right_10" src="" alt="">
<div class="f_left product_description">
<span class="f_size_medium"></span>
</div>
<div class="f_left f_size_medium">
<div class="clearfix">
1 x <b class="color_dark">$99.00</b>
</div>
<button class="close_product color_dark tr_hover"><i class="fa fa-times"></i></button>
</div>
</div>
</li>
</ul>
i am using jquery to bind this ul tag. Following is my jquery code to bind to the ul tag
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
id = 1;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Default.aspx/BindCart",
data: "{'UID':'" + id + "'}",
dataType: "json",
async: true,
success: OnImageSuccess,
error: OnImageError,
failure: function (response) {
alert('Fail');
}
});
function OnImageSuccess(response) {
var ulProductCart = document.getElementById("ulProductCart");
$.each(response.d, function (key, value) {
ulProductCart.append("<li><div><img src=" + value.ImgProduct + " style=width:50px height:50px /><div><a>" + value.ProductName + "</a><span>" + value.ProductCode + "</div><div><div>1*<b>" + value.Price + "</b></div><button><i></i></button></div> </div></li>");
})
alert('succeed');
}
function OnImageError(response) {
alert(response.d);
}
});
</script>
My Web Method is:
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod(enableSession: true)]
public static Products[] BindCart(string UID)
{
DataTable dt = new DataTable();
List<Products> details = new List<Products>();
//HtmlAnchor a = new HtmlAnchor();
//a.InnerHtml
dt = new ProductImages().SelectProductsWithImagesByProductID(Convert.ToInt64(UID));
foreach (DataRow dtrow in dt.Rows)
{
Products Products = new Products();
Products.ProductCode = dtrow["ProductCode"].ToString();
Products.ProductName = dtrow["ProductName"].ToString();
Products.ImgProduct = dtrow["ImgProduct"].ToString();
Products.Price = Convert.ToDecimal(dtrow["Price"].ToString());
details.Add(Products);
}
return details.ToArray();
}
My above code fetches the appropriate data from database but when it goes to bind the ul tag it dows not gets bind.Also it goes to OnImageSuccess Mrthod used in jquery but my ul tag is not getting bind.
Issue in the below line
var ulProductCart = document.getElementById("ulProductCart"); // not a jQuery object
append is a jQuery function , so u need to use jquery selector.
use this :
var ulProductCart = $("#ulProductCart");
Sample :
function OnImageSuccess(response) {
// var ulProductCart = document.getElementById("ulProductCart");
var ulProductCart = $("#ulProductCart");
$.each(response.d, function (key, value) {
ulProductCart.append("<li><div><img src=" + value.ImgProduct + " style=width:50px height:50px /><div><a>" + value.ProductName + "</a><span>" + value.ProductCode + "</div><div><div>1*<b>" + value.Price + "</b></div><button><i></i></button></div> </div></li>");
})
alert('succeed');
}

Categories

Resources