Jquery Auto complete extender not working after postback - c#

Im using jQuery Autocomplete using Web Service in ASP.Net.I've used the autocomplete to filter employeecode.When the page loads autocomplete works fine,but after when i click the search button autocomplete is not working properly.
I think the problem lies in document.ready function,so when the page loads it works fine,But i've to use autocomplete after the buttonclick event also.
How can i do this ???
Heres my jQuery Autocomplete
<link href="../AutoComplete/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="../AutoComplete/jquery.min.js" type="text/javascript"></script>
<script src="../AutoComplete/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%=txtEmpcode.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/MyWebService.asmx/FetchEmpCode") %>',
data: "{ 'Empcode': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[1],
//val: item
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
minLength: 1
});
});
</script>
Markup
<td align="right">
<asp:Label ID="lblEmpCodeSrch" runat="server" Text="EmpCode" CssClass="label"> </asp:Label>
</td>
<td>
<asp:TextBox ID="txtEmpCodeSrch" runat="server" Width="250px" ToolTip="Enter Employeecode"></asp:TextBox>
<asp:Button ID="bttnSearch" runat="server" CssClass="submit" Height="23px" Text="Search" onclick="bttnSearch_Click" />
</td>
ButtonSearch Codebehind
protected void bttnSearch_Click(object sender, EventArgs e)
{
clsEmp.EMPLOYEEID =txtEmpCodeSrch.Text.Trim()==""? 0:Convert.ToInt32(hFieldEmpId.Value);
DataTable dtEmp = clsEmp.GetDetails();
if (dtEmp.Rows.Count > 0)
{
hFieldEmpId.Value = "";
// txtEmpCodeSrch.Text = "";
if (ViewState["Sort"] != null)
{
DataView dView = new DataView(dtEmp);
dView.Sort = ViewState["Sort"].ToString();
gdView.DataSource = dView;
gdView.DataBind();
}
else
{
gdView.DataSource = dtEmp;
gdView.DataBind();
}
}
}

When you have an UpdatePanel, after the update of the data, you also need to re-initialize the javascript, because the old one is not longer working, because the struct of your html page have change, the dom have change.
The UpdatePanel is giving some function to do that on client side, and your code will be as:
<script type="text/javascript">
// if you use jQuery, you can load them when dom is read.
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
// Place here the first init of the autocomplete
InitAutoCompl();
});
function InitializeRequest(sender, args) {
}
function EndRequest(sender, args) {
// after update occur on UpdatePanel re-init the Autocomplete
InitAutoCompl();
}
function InitAutoCompl() {
$("#<%=txtEmpcode.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/MyWebService.asmx/FetchEmpCode") %>',
data: "{ 'Empcode': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[1],
//val: item
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
minLength: 1
});
}
</script>

I tell you that I could solve the problem by adding a Triggers within the UpdatePanel tag, thus achieves the desired behavior in my case. I hope you can serve you as me helped me.
<ajax:UpdatePanel>
<ContentTemplate>
//My label fire autocomplete
<asp:TextBox id="MyLabelForAutoComplete" runat="server"/>
// Other Html Tags...
<Triggers>
<ajax:PostBackTrigger ControlID="MyLabelForAutoComplete">
</Triggers>
</ajax:UpdatePanel>

Related

Can't send a basic, non MVC form using ajax in .Net (C#)

I have seen answers to this question many times, but most of them are related to MVC controllers.
The issue I am having while trying to send a form using Ajax is that while in debug mode, the execution flow won't reach the break point I have in my code behind. Also, I notice that when I click in the submit button, the page refreshes very quickly; I though that the whole idea of ajax was to not refresh the page.
This is my index.aspx
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="ajaxform.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<fieldset class="fs1">
<input id="inputData" tabindex="1" name="theinputData" class="field" placeholder="Paste URL, docId or docSetId" runat="server"/>
<input id="form1Send" type="submit" class="button" onclick="submit()"/>
</fieldset>
</div>
</form>
</body>
Here is the code of my ajaxform.js
$(document).ready(function () {
$('#form1').submit(function (e) {
var formData = new FormData(this);
$.ajax({
url: 'index.aspx/OnSubmit',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: formData,
contentType: false,
processData: false,
success: function (result) {
alert("We returned: " + result);
},
error: function (result) {
alert("Error");
}
});
e.preventDefault();
});
});
Finally, here is my code behind
namespace mySpace
{
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string OnSubmit()
{
return "I was in code behind";
}
}
}
My break point is on the return line. Why the program never reach the WebMethod?
There are a couple of issues with your code:
You're double declaring something to handle the form. Your form1send button has onclick="submit()" in it as well as the form submit handler you're wiring up via jQuery
The content of your JavaScript handler is slightly off, for example you set contentType twice.
Here's a simplified version of the JavaScript that works on my machine:
$(document).ready(function () {
$('#form1').submit(function (e) {
$.ajax({
type: "POST",
url: "index.aspx/OnSubmit",
contentType: "application/json; charset=utf-8",
data: '{}',
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (response) {
}
});
e.preventDefault();
});
});
NOTE: I based this (the content of the $.ajax call) on a code sample I found elsewhere, which is why the parameters and order of the parameters are different to yours.
If your app has a RouteConfig.cs file present, you may also need to change settings.AutoRedirectMode = RedirectMode.Permanent; to settings.AutoRedirectMode = RedirectMode.Off; if you see an HTTP 401 error in your browsers developer tools console for the request to your WebMethod decorated method in index.aspx.
By executing event.preventDefault() before FormData(this) a premature refresh is prevented.
See below:
$(document).ready(function () {
$('#form1').submit(function (event) {
event.preventDefault();
var formData = new FormData(this);
$.ajax({
url: 'index.aspx/OnSubmit',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: formData,
contentType: false,
processData: false,
success: function (result) {
alert("We returned: " + result);
},
error: function (result) {
alert("Error");
}
});
});
});

Call asp.net function from javascript function

I want to call asp.net function from a javascript function passing string value.
this is the asp.net function :
[System.Web.Services.WebMethod]
public static string InsertData(string ID)
{
string source = "Data Source=(LocalDB)\v11.0;Integrated Security=True;Connect Timeout=30";
using(SqlConnection con = new SqlConnection(source))
{
using (SqlCommand cmd = new SqlCommand("Insert into Book (Name) values(#Name)", con)) {
con.Open();
cmd.Parameters.AddWithValue("#Name", ID);
cmd.ExecuteNonQuery();
return "True";
}
}
}
So i want to call this function from javascript function which passes the string value "ID" to the the asp.net function.
this is the javascript function i use
function CallMethod() {
PageMethods.InsertData("hello", CallSuccess, CallError);
}
function CallSuccess(res) {
alert(res);
}
function CallError() {
alert('Errorrr');
}
and i call it from here
<body>
<header>
</header>
<div class="table" id="div1" > </div>
<form id="Form1" runat="server">
<asp:Button id="b1" Text="Submit" runat="server" onclientclick="CallMethod();return false;"/>
<asp:ScriptManager enablepagemethods="true" id="ScriptManager1" runat="server"></asp:ScriptManager>
</form>
</body>
so i have a button and onClick i want to add "Hello" Row to my table but nothing happens and CallError function calls
You can call web method from ajax call in javascript . you need to set url parameter values to function you want to call and you can pass value in the data prameter in json formate.
like this data:"{ParamterName:'VALUE'}
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "YourPage.aspx/YouPageMethod",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('Method Called Sucess fully');
},
error: function (result) {
alert("error " + result);
}
});
});
</script>
OR
you can call using PageMethod Eample
<script type="text/javascript">
function callInsert() {
PageMethods.InsertDate(id, OnSucceeded, OnFailed);
}
function OnSucceeded(response) {
alert(response);
}
function OnFailed(error) {
alert(error);
}
/* call this javascript function */
callInsert();
</script>
You will need to include Jquery first in your page. Then you need to add the following Javascript code.
<script type="text/javascript">
var id ="5"; //your id will be stored here
$(document).ready(function () {
$.ajax({
type: "POST",
url: "YourPage.aspx/InsertData" + "&?id=" ,
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('Success');
},
error: function (xhr, request, status) {
alert(xhr.responseText);
}
});
});
</script>
You need to have scriptManager in your .aspx page
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
After that you can call the method using
<script type="text/javascript">
function func(){
PageMethods.InsertData(id,success_msg,failure_msg);
}
</script>

How to find text-box in GridView using Javascript

I am trying to get access and find text-box in GridView using javascript but i am getting an error: 'The name txt_UID' does not exist in the current context'. Everything worked fine when my text-box was outside of the GridView. Here is my text-box in the gridview and my gridview is called GridView1:
<asp:TemplateField ItemStyle-Width="150px" HeaderText="User Assigned">
<ItemTemplate>
<asp:TextBox ID="txt_UID" runat="server" Text='<%# Eval("UID")%>'
CssClass="AutoCompleteTextBox" Width="130px" BackColor="LightGoldenrodYellow"></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
Here is my JavaScript:
<script type ="text/javascript">
function setAutoComplete() {
var textBoxes = document.getElementsByClassName("AutoCompleteTextBox");
for (var i = 0; i < textBoxes.length; i++) {
addAutoComplete(textBoxes[i].id);
}
}
</script>
<script type="text/javascript">
function addAutoComplete(textBoxId) {
$("#" + textBoxId).autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Service.asmx/GetUserNames") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#<%=hfUserId.ClientID %>").val(i.item.val);
},
minLength: 1
});
};
<script type ="text/javascript">
$(document).ready(function () { setAutoComplete(); });
</script>
The problem is your GridView creates a TextBox on each row. There is no "txt_UID" control outside of the GridView. That is what your error message is telling you.
Your JavaScript function is designed to work with one TextBox. I imagine you want the AutoComplete to work on ALL TextBox controls in the GridView.
My suggestion would be to change the JavaScript function to take a parameter with the TextBox ID and then add a CSS class to each TextBox, and finally make a wrapper JavaScript function that will enumerate the TextBox controls using getElementsByClassName, and call that wrapper function on DOM ready.
Here's what it will look like:
Add CSS class to the TextBoxes:
<asp:TemplateField ItemStyle-Width="150px" HeaderText="User Name">
<ItemTemplate>
<asp:TextBox ID="txt_UID" runat="server" Text='<%# Eval("UID")%>'
CssClass="AutoCompleteTextBox" Width="130px" BackColor="LightGoldenrodYellow"></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
New JavaScript function:
function setAutoComplete()
{
var textBoxes = document.getElementsByClassName("AutoCompleteTextBox");
for (var i = 0; i < textBoxes.length; i++)
{
addAutoComplete(textBoxes[i].id);
}
}
Next, make your other JavaScript into a function that takes a parameter (the id):
function addAutoComplete(textBoxId) {
$("#" + textBoxId).autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Service.asmx/GetUserNames") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#<%=hfUserId.ClientID %>").val(i.item.val);
},
minLength: 1
});
};
Finally, your on ready code changes to just call the wrapper function you created:
$(document).ready(function () { setAutoComplete(); });
Bonus: Here's a way to do it with jQuery only:
(just requires the CSS class on the TextBoxes)
$(document).ready(function () {
$.each($(".AutoCompleteTextBox"), function (i, textBox) {
textBox.autocomplete( /* your code */);
})
});
Your Gridview will be rendered as Table and your control will be contained in cell of table. You can give a try to following.
<script type=”text/javascript”>
$(document).ready(function(){
tblTable=document.getElementById(‘<<Client ID of the GridView>>’);
Cell=tblTable.rows[i].cells[j];//i and j are locations of that cell.
FirstControl = Cell.childNodes[0];
});
</script>
replace <<Client ID of the GridView>> with id of your GridView
you can use name attribute and the grid id to find it:
<asp:TextBox ID="txt_UID" name="mytextbox" runat="server" Text='<%# Eval("UID")%>'
Width="130px" BackColor="LightGoldenrodYellow"></asp:TextBox>
the javascript part:
$("#<%=MyGrid.ClientID %>[name=mytextbox]").autocomplete({});

AutoPopulate DropDownList Using Ajax

I have 2 dropdownlist which is already binded on pageload , i want to rebind these two dropdownlist after firing a ajax function.Here i have written a sql server stored procedure to get the data which is needed to dropdownlists.But how i will get the value to dropdownlist,so that it can bind the new data using ajax function.The screen is developed by using Asp.net C# coding.
Here is the drop down list of the asp.net
<asp:DropDownList id="ddlCourse" runat="server" AutoPostBack="false"
Height="28px" title="Select Course" Width="290px"
></asp:DropDownList>
and here is the jquery method that is calling the web service method
function BindCourse() {
$.ajax({
type: "POST",
url: "/WebService/CollegeWebService.asmx/GetCourseDetails",
data: "{}",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnCoursePopulated,
error: function (xml, textStatus, errorThrown) {
alert('error');
alert(xml.status + "||" + xml.responseText);
}
});
}
This is the method to That is used in the ajex call method and call the PopulateControl method to bind the Drop down List
function OnCoursePopulated(response) {
PopulateControl(response.d, $('#<%=ddlCourse.ClientID %>'));
}
Here is the description of the PopulateControl Method
function PopulateControl(list, control) {
if (list.length > 0) {
control.removeAttr("disabled");
control.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(list, function () {
control.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
else {
control.empty().append('<option selected="selected" value="0">Not available<option>');
}
}
Thus you finally bind the drop down list
You can try the following as a demo. Server side DropDownLists are replaced with HTML select elements so that exception "Invalid postback or callback argument" doesn't happen.
Drawback in this demo is that the values are not restored on form after postback. You can put this inside a form in Default.aspx:
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function populate(populateInitial) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/Default.aspx/populate',
data: "{'populateInitial': '" + populateInitial + "'}",
dataType: "json",
async: false,
success: function(result) {
var ddlItems = document.getElementById('ddlItems');
ddlItems.options.length = 0;
$.each(result.d, function(key, item)
{ ddlItems.options[key] = new Option(item); });
}
});
}
</script>
<form id="form1" runat="server">
<div>
<select id="ddlItems" name="ddlItems">
</select>
<br />
<input type="button" onclick="populate('0');" value="Change values" />
<br />
Selected item:
<asp:Label ID="lblSelectedItem" runat="server" Text=""> </asp:Label>
<br />
<asp:Button ID="Button1" runat="server"
Text="Write out selected item text" />
</div>
<script type="text/javascript">
populate('1');
</script>
And you put these methods inside Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
lblSelectedItem.Text = Request["ddlItems"].ToString();
}
}
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static List<string> populate(string populateInitial)
{
if (populateInitial == "1")
return (new string[] { "a", "b" }).ToList();
else
return (new string[] { "c", "d", "e", "f" }).ToList();
}
You should make Ajax call to some sort of page (I advice you to add Generic Hanlder) which responses xml or json or even html, of drop down values and textfield values, than read it in javascript jquery and generate html for your drop down which is the following
<select id="ddl">
<option value="value">text</option>
</select>
you should read "value" & text and generate this> <option value="value">text</option>
and append to ddl

Autocomplete JQuery is not working

Merged with jQueryUI Autocomplete Plugin not working.
I am NEW in JQ stuff. So basically I have a simple textbox in which I want user to search some items. I am using JQ for this. I read this link which implements this example:
http://aspnetnova.blogspot.com/2009/06/simple-jquery-ajax-server-side.html
Here is my code:
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<style type="text/css">
.login
{}
</style>
<script type ="text/javascript">
var data = "";
$(document).ready(function () {
$("#tbSearch").click(function () {
$.ajax({
type: "POST",
url: "AgentList.aspx/LoadData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
data = msg.d.split(" ");
$('#<%= tbSearch.ClientID %>').autocomplete(data);
}
});
});
});
</script>
</asp:Content>
<asp:TextBox ID="tbSearch" runat="server" ontextchanged="tbSearch_TextChanged"></asp:TextBox>
Here is my code behind:
#region "Auto Complete"
[System.Web.Services.WebMethod]
public static string LoadData()
{
return "S M SMI SM A ABC ABCD ABCI";
}
#endregion
What I am doing wrong here?

Categories

Resources