I'm trying to write some JQuery using the AutoComplete plugin to display a list of names to the user as the user starts to type in the names (see code below). The code is working fine unless the user starts backspacing to change the name of the user entered, which causes it to write new values over the existing ones in the autocomplete results. Is there something I'm doing wrong here, maybe by using the keyup function to kick off the autocomplete, or is there some way to clear the existing autocomplete results if the user starts to backup?
Here is the JQuery code in the markup file in Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="js/jquery-1.3.2.js" ></script>
<script type="text/javascript" src="js/jquery.autocomplete.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
$("#example").keyup(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetCustomerNames",
data: "{ searchParam: '" + $("#example").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#example").autocomplete(msg.d,
{ scroll: false, max: 10, width: 250, selectFirst: true });
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Customer Name: <input id="example" autocomplete="off" type="text" />
</div>
</form>
</body>
</html>
And here is the code in my Default.aspx.cs codebehind file returning the data:
[WebMethod]
public static string[] GetCustomerNames(string searchParam)
{
List<string> data = new List<string>() { "Andrew", "Ramona", "Russ", "Russell", "Raymond", "Annette", "Anthony" };
List<string> names = new List<string>();
foreach (string s in data)
{
if (s.ToLower().StartsWith(searchParam))
{
names.Add(s);
}
}
return names.ToArray();
}
I was under the impression that you could give a search page as the first parameter to the autocomplete function.
$(document).ready(function(){
$("#example").autocomplete("Default.aspx/GetCustomerNames", { scroll: false, max: 10, width: 250, selectFirst: true });
});
Something like that, you may need to find out the correct options to use to get it to do what you want, but at least it won't be reinstalling the autocomplete after each keyup.
Related
This question already has an answer here:
How to refer http handler file from jQuery ajax under different directory of asp.net web application
(1 answer)
Closed 5 years ago.
I created a http handler file in following directory of my application
I am referring this handler from common.js file using jQuery ajax and common.js file referred in aspx pages StoresSummary.aspx & EmoloyeeProfile.aspx
From EmoloyeeProfile.aspx I am able to call the handler and getting the output, but from StoresSummary.aspx jquery ajax call getting failed.
I know the cause of failure because the path of CommonHandler.ashx file does not map correctly due to location hierarchy of StoresSummary.aspx.
This is a sample code I am posting, the http handler file I need to call from jQuery ajax and aspx pages may exists in different directory of same web application.
How do I give path of CommonHandler.ashx in ajax jQuery call so any location hierarchy of my aspx page can call it.
This is my code
common.js
function GetMessage(key) {
var message = '';
$.ajax({
type: 'POST',
url: '../../Common/Handlers/CommonHandler.ashx', /*Working for EmoloyeeProfile.aspx but not for StoresSummary.aspx*/
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: { 'MessageKey': key },
success: onSucess,
error: OnFailed,
async: false
});
function onSucess(res) {
message = res;
}
function OnFailed(res) {
alert('failed');
}
return message;
}
CommonHandler.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
namespace DemoWebApp.Common.Handlers
{
/// <summary>
/// Summary description for CommonHandler
/// </summary>
public class CommonHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(GetData(context.Request["MessageKey"]));
context.Response.ContentType = "text/html";
context.Response.Write(result);
}
private string GetData(string Id)
{
return DateTime.Now.ToString(); //just to demostrate
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
StoresSummary.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="../../../Common/Scripts/common.js"></script>
<script src="../../../Common/Scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Get Message" OnClientClick="return CallMethod();" />
</div>
</form>
<script type="text/javascript">
function CallMethod() {
var msg = GetMessage('001');
alert(msg);
return false;
}
</script>
</body>
</html>
EmoloyeeProfile.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="../Common/Scripts/common.js"></script>
<script src="../Common/Scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Get Message" OnClientClick="return CallMethod();" />
</div>
</form>
<script type="text/javascript">
function CallMethod() {
var msg = GetMessage('001');
alert(msg);
return false;
}
</script>
</body>
</html>
Provide absolute path to the handler. You are providing relative path now. See the ajax url section.
$.ajax({
type: 'POST',
url: '/Common/Handlers/CommonHandler.ashx', /*Working for EmoloyeeProfile.aspx but not for StoresSummary.aspx*/
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: { 'MessageKey': key },
success: onSucess,
error: OnFailed,
async: false
});
I'm using Visual Studio 2015 and the project is in .NET 4.5.2
I choose the default template so there are some things like the Master Site and Default.aspx that are in the solution but I have not touched them...
I added a page, Welcome.aspx and Can't seem to get the PageMethods to work properly.
Welcome.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Welcome.aspx.cs" Inherits="MyProject.Welcome" %>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.0.3/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.0.3/dist/leaflet.js"></script>
<link rel="stylesheet" href="CSS/WelcomeCSS.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css" />
</head>
<body>
<form id="WelcomeForm" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server"></asp:ScriptManager>
<div> ... some more html... non <asp:controls>...</div>
<script type="text/javascript">
//PageMethods.TestMarker(); // throws exception - PageMethods is undefined.
$.ajax({
type: "POST",
dataType: 'text',
contentType: "text",
url: "Welcome.aspx/TestMarker()",
data: "{val = adrian}", // parameters for method
success: function (dt) { alert("HI"+dt); }, //all Ok
error: function (dt) { alert(dt); } // some error
}); // doesn't seem to throw an error but C# never gets called
</script>
</form>
</body>
</html>
Welcome.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace HomeVenues
{
public partial class Welcome : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
protected static void TestMarker(string val)
{
return;
}
}
}
I have the following references:
- system.web.extensions
Q: What am I missing to call my server side code?
Try making changes to the below lines of code:
public static void TestMarker(string val) //Method should be public
url: "Welcome.aspx/TestMarker", //Dont need enclosing braces
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({val:"adrian"}),
Change your Protected WebMethod to Public as follows :
[WebMethod]
Public static void TestMarker(string val)
{
return;
}
Change your client side script ajax call as follows :
<script>
$.ajax({
type: "POST",
dataType: 'text',
contentType: "text",
url: "Welcome.aspx/TestMarker",
data: '{ val:"adrian" }', // parameters for method
success: function (data) { alert("HI" + data.d); }, //all Ok
error: function (data) { alert(data); } // some error
});
</script>
Explanation :- Do remember following points :
public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.
protected
The type or member can only be accessed by code in the same class or struct, or in a derived class.
private
The type or member can only be accessed by code in the same class or struct.
I am trying to implement jquery autocomplete textbox in asp.net. But I am getting the error "Object doesn't support this property or method" though while coding I am getting 'autocomplete' function in intellisense. I have tried to use google api link as well in case my jquery files are not getting loaded correctly, but i am getting the same error. Following is my code:
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script src="Scripts/jquery-1.11.2.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui.js" type="text/javascript"></script>
<link href="Styles/jquery-ui.css" rel="stylesheet" type="text/css" />
<script language="JavaScript" type="text/JavaScript">
$(document).ready(function () {
$("[id*=txtPCTrx]").autocomplete({
source: function (request, response) {
$.ajax({
url: "PCAdd.aspx/GetAutoCompleteData",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{'txt':'" + $('[id*=txtPCTrx]').val() + "'}", //json to represent argument
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item,
value: item
}
}))
//debugger;
},
error: function (result) {
alert("Error");
}
});
},
minLength: 1,
delay: 1000
});
</script>
Apart from the above autocomplete function I have many other jquery functions which are working properly in the same page. Please help.
In an Asp.Net application I need the jQuery progress bar that runs till the data is not saved in database
For this I created a web service and the Ajax jQuery function and the progress bar Javascript plugin
HTML
<div id="progressbar"></div>
<div id="result"></div>
<asp:Label runat="server" ID="lbldisp" Text= "Percentage Completed : "/>
<asp:Label runat="server" ID="lblStatus" />
<asp:Button ID="btnSave" runat="server" Text="Save" class="buttonstyle" />
Script (I am using Sys.Application.add_load instead of document.ready function due to DOM Interruption )
<link type="text/css" href="CSS/ui.all.css" rel="stylesheet" />
<script src="js/jquery-1.8.1.js" type="text/javascript"></script>
<script src="js/ui.core.js" type="text/javascript"></script>
<script src="js/ui.progressbar.js" type="text/javascript"></script>
<script type="text/javascript">
Sys.Application.add_load(function() {
// jquery Progress bar function.
$("#progressbar").progressbar({ value: 0 });
$("#lbldisp").hide();
//button click event
$("#ctl00_ContentPlaceHolder1_btnSave").click(function() {
$("#ctl00_ContentPlaceHolder1_btnSave").attr("disabled", "disabled")
$("#lbldisp").show();
//call back function
var intervalID = setInterval(updateProgress, 250);
$.ajax({
type: "POST",
url: "JobCard.aspx/InsertData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
$("#progressbar").progressbar("value", 100);
$("#lblStatus").hide();
$("#lbldisp").hide();
$("#result").text(msg.d);
clearInterval(intervalID);
}
});
return false;
});
});
function updateProgress() {
var value = $("#progressbar").progressbar("option", "value");
if (value < 100) {
$("#progressbar").progressbar("value", value + 1);
$("#lblStatus").text((value + 1).toString() + "%");
}
}
</script>
Web service
[System.Web.Services.WebMethod]
public static string InsertData()
{
fortest jobcardForm = new fortest();
//this is a line 760 --> jobcardForm.Insert_OilService();
jobcardForm.Insert_TuningService();
jobcardForm.Insert_OtherServices();
jobcardForm.Insert_QRCService();
jobcardForm.Insert_problemTaken();
jobcardForm.Insert_ActionTaken();
jobcardForm.Insert_SpareParts();
//Insert_Technician();
dsJobCardTableAdapters.Select_JobCarRegistrationTableAdapter insertjobcard = new dsJobCardTableAdapters.Select_JobCarRegistrationTableAdapter();
string a = insertjobcard.Insert_JobCarRegistration(
jobcardForm.txtdate.Text, jobcardForm.txtTimeIn.Text,
jobcardForm.txtTimeOut.Text, jobcardForm.Txt_RegNo.Text,
jobcardForm.Txt_FleetNo.Text,
jobcardForm.chkbkdvechle.Checked, jobcardForm.chkwalkin.Checked,
jobcardForm.chkRepeatJob.Checked,
jobcardForm.txtCustomerName.Text, jobcardForm.txtRiderName.Text,
jobcardForm.txtPhoneNo.Text, jobcardForm.txtEmail.Text,
Convert.ToInt32(jobcardForm.ddl_ServiceAdvisor.SelectedValue),
Convert.ToInt32((jobcardForm.ListBox1.SelectedValue == "" ? "0" : jobcardForm.ListBox1.SelectedValue)),
jobcardForm.ddl_Model.SelectedValue,
jobcardForm.ddl_type.SelectedValue, jobcardForm.txtKMSRUN.Text,
jobcardForm.ddl_color.SelectedValue
, "1", HttpContext.Current.Session["user_id"].ToString(),
jobcardForm.txtdateout.Text, jobcardForm.txtchassis.Text,
jobcardForm.ddlyear.SelectedValue, jobcardForm.txtexpirydate.Text,
jobcardForm.txtnotes.Text,
jobcardForm.ddllocation.SelectedValue).ToString();
HttpContext.Current.Response.Redirect(HttpContext.Current.Request.RawUrl);
return "Save Completed...";
}
Looks like the script is working fine but I am getting an error in the web browser console Window and the error is "500 Internal Server Error" at line 760 in web service jobcardForm.Insert_OilService();. But when I use the web service code in server side onclick event the data is inserted into the database. I need the progress bar, that's why I have to change the logic using web service
ERROR
I normally create an object of a class to use it in a static method and this was the simplest way to use a non-static method in a static method.
Why dont you do something like this:
function FunctionName() {
$.ajax({
type: "POST",
url: ,
data: JSON.stringify(),
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
$("#progress-bar").show();
$("#progress-bar1").hide();
},
complete: function () {
$("#progress-bar").hide();
$("#progress-bar1").show();
},
success: function () {
}
});
}
And have 2 div
<div class="gap"></div>
<div id="progress-bar" style="display:none;">
<img src="~/Images/ajax-progressbar.gif" />
</div>
<div id="progress-bar1"></div>
</div>
So before you send your request you show $("#progress-bar").show(); once once the content loaded you hide it. Hope this answer your question.
How to send xml parameter to call WCF method? My client side code is in AJAX,JSON using jQuery.I want to pass xml value as parameter.How to pass xml value?
My xml value is
<value><Root>mydata</Root></value>
My client side code--
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js"></script>
<script type="text/javascript" >
jQuery.support.cors = true;
var bhRequest = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<s:Body>" +
"<GetSMC xmlns=\"http://tempuri.org/\">" +
"<value><Root>MyValue</Root></value>" +
"</GetSMC>" +
"</s:Body>" +
"</s:Envelope>";
$(document).ready(function () {
$("#btnWCFBasicHttp").click(function () {
alert("hi");
$.ajax({
type: "POST",
url: "http://localhost:8130/MyService.svc/bh/",
data: bhRequest,
timeout: 10000,
contentType: "text/xml",
dataType: "xml",
beforeSend: function (xhr) {
xhr.setRequestHeader("SOAPAction", "http://tempuri.org/IMyService/GetSMC");
},
success: function (data) {
alert("success");
$(data).find("GetSMCResponse").each(function () {
document.getElementById('Label2').innerHTML = $(this).find("GetSMCResult").text();
});
},
error: function (xhr, status, error) {
alert(error);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="btnWCFREST" type="button" value="Call WCF using JQuery" />
<label ID="Label1" runat="server" Text="Label"></label>
</div>
</form>
</body>
</html>
I'm not sure if it'll work, but try to put that XML inside
<![CDATA[ and ]]>
There is also some hack with string tag, but I don't know if it is necessary (maybe only CDATA tag will be enough):
WCF RESTFul service - Pass XML as string to service
you will encrypt by base64 and pass it,on the server client you can decrypt