jQuery Autocomplete Doesn't Invoke For Textbox in ASP.NET - javascript

I'm trying to use a jquery autocomplete script within an asp.net project somebody else wrote. Although i can run it in a seperated project, it doesn't do anything when implemented inside the project i mentioned. They both are on .net 4.0 framework. html code of the page is like this:
<%# Page Title="" Language="C#" MasterPageFile="~/site.master" AutoEventWireup="true" CodeFile="Meslek.aspx.cs" Inherits="AutoComplete.Scripts_Meslek" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#ContentPlaceHolder1_txtCountry").autocomplete({
source: function (request, response) {
var param = { keyword: $('#ContentPlaceHolder1_txtCountry').val() };
$.ajax({
url: "Meslek.aspx/GetCountryNames",
data: JSON.stringify(param),
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: 1
});
});
</script>
<div>
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
<br />
</asp:Content>
I think the problem is this row below should invoke the function to retrieve the autocomplete words from code behind, but whatever i enter into the textbox, nothing happens.
$("#ContentPlaceHolder1_txtCountry").autocomplete({
I know the code works becuase i use it in different projects, but when i implemented it on this project, i got nothing. I know the List that is returned form the code behind works and if i could call the function there, i am sure that i will retrieve the results.
So the question is, what might be the cause of this? Is this caused by some project properties, is it caused by the master page, is my code to invoke the function is wrong or is it something else?
The entire code in Meslek.aspx is below
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Data.SqlClient;
using System.Web.Configuration;
namespace AutoComplete
{
public partial class Scripts_Meslek : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string[] GetCountryNames(string keyword)
{
List<string> country = new List<string>();
//string query = string.Format("SELECT DISTINCT Country FROM Customers WHERE Country LIKE '%{0}%'", keyword);
string query = string.Format("SELECT mslk FROM meslek WHERE mslk LIKE '%{0}%'", keyword);
using (SqlConnection con =
//new SqlConnection("Data Source=KMISBPRDSQL001; Database=SIRIUS; Initial Catalog=SIRIUS; Trusted_Connection=True; "))
new SqlConnection(WebConfigurationManager.ConnectionStrings["SIRIUS"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
country.Add(reader.GetString(0));
}
}
}
return country.ToArray();
}
}
}

I suggest using this:
use function :
function CompleteText() {
$(document).ready(function () {
$(".Country").autocomplete({
source: function (request, response) {
var param = { keyword: $('.Country').val() };
$.ajax({
url: "Meslek.aspx/GetCountryNames",
data: JSON.stringify(param),
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: 1
});
});
}
In TextBox:
<asp:TextBox ID="txtCountry" onfocus="CompleteText()" runat="server" class="Country" Width="298px"></asp:TextBox>

Related

two user controls in the same page using jquery do not work

I have two same user control in Mizan.aspx.I want to use autocomplete
txtHesapKodu in belHesapPlani(it is usercontrol).When i write anything in the
first user control textbox,it works and everything is fine.On the other
hand,While I write in the second user control textbox,it is not work and do not
run GetHesapKodu function that is used.
$(document).ready(function () {
SearchText();
//$('txtHesapKodu').keyup(function () {
// SearchText();
//});
});
function SearchText() {
$("#txtHesapKodu").autocomplete({
source: function (request, response) {
//alert("user controldeyizx");
// alert(document.getElementById('txtHesapKodu').value.uniqueID);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../../jqueryTEST.asmx/GetHesapKodu",
//url: "belHesapPlani.ascx/GetHesapKodu",
data: "{'hesapKodu':'" + document.getElementById('txtHesapKodu').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("No Match");
}
});
}
});
}
Mizan.aspx
<td>
<uc12:belHesapPlani runat="server" ID="belHesapPlani1" ClientIDMode="AutoID" Enabled="true" />
</td>
</tr>
<tr>
<td>
<uc12:belHesapPlani runat="server" ID="belHesapPlani2" ClientIDMode="AutoID" Enabled="true" />
</td>
[System.Web.Script.Services.ScriptMethod]
[WebMethod(EnableSession = true)]
public List<string> GetHesapKodu(string hesapKodu)
{
DataTable dt = new MH_HESAP_PLANI().GetAllByHesapNameIdKurum(1, "HESAP_KODU", hesapKodu, null);
List<string> strList = new List<string>();
foreach (DataRow item in dt.Rows)
{
strList.Add(item["NAME"].ToString());
}
return strList;
}
You are filtering for #txtHesapKodu in SearchText() but please keep in mind that the # filters for an ID and IDs are unique across the whole site. So you cannot have an element with the same ID in 2 different user controls. Use the name attribute instead and filter (Name=[txtHesapKodu]) instead.

Ajax Call in Asp.net ([WeBMethod] Function not calling)

I am developing a quite large application. But I am facing problem in Ajax. For that I tried to make a new and short program to invoke Ajax for test purpose. But I am stuck in that.
Here is the Test.aspx code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Testing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="test.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
</form>
</body>
</html>
Ajax function is
$(document).ready(function () {
$("#Button1").click(function () {
var text = $("#TextBox1").val();
text = "this is test";
debugger
$.ajax({
type: "POST",
contentype: "application/json; charset=utf-8",
url: "Test.aspx/Test",
data: { str: text},
//dataType:"json",
success: function (data) {
alert("yes");
},
error: function (response) {
debugger
alert(response);
}
});
return false;
});
});
And Test.aspx.cs code is below
[WebMethod]
public void Test(string str)
{
Console.WriteLine(str);
}
When I put some value in TextBox. It alerts Yes!. But does not invoke [WebMethod].
Anyone know the problem.
Make your [WebMethod] static as
[WebMethod]
public static void Test(string str)
{
//Console.WriteLine(str);
string retstr=str;
}
change ajax data value to data: "{'str':'" + text + "'}"
UPDATE
Try This Same Code
aspx:
<asp:Button ID="Button1" ClientIDMode="Static" runat="server" Text="Button" />
aspx.cs
[WebMethod]
public static void Test(string str)
{
string abc=str;//Use this wherever you want to, check its value by debugging
}
test.js
$(document).ready(function () {
$("#Button1").click(function () {
var text = "this is test";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Test.aspx/Test",
data: "{'str':'" + text + "'}",
dataType:"json",
success: function (data) {
alert("yes");
},
error: function (response) {
alert(response);
}
});
});
});
This is working
C#
[WebMethod]
public static string Test(string str)
{
return str;
}
JS
const text = "this is test";
$.ajax({
url: "Test.aspx/Test?str="+text,
contentType: "application/json; charset=utf-8",
method: 'post',
data: "{'str':'"+text+"'}",
success: function (data) {
console.log(data);},
error: function (response) {
debugger;
console.log(response); }
});
Have you tried setting ScriptMethod attribute for your method like so:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

Auto complete in asp.net using jquery

Here I'm trying to use jquery auto complete in asp.net, I'm trying to retrieve the data from sql data source and use that for auto fetch. while I running the code auto complete have not worked.
my code
<script src="jquery.min.js" type="text/javascript"></script>
<script src="jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Inventory.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtPartno').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
textbox field
<asp:TextBox ID="txtPartno" CssClass="Textboxbase" class="autosuggest" runat="server"></asp:TextBox>
and my c# code
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=MYPC-GN\\KASPLDB;Integrated Security=False;User ID=sa;Password=*****;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT PART_NO from Inventory where UserName LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["UserName"].ToString());
}
return result;
}
}
}
One problem which I can see is your javascript call is little wrong. You cannot get the value of textbox which is created by asp itself with document.getElementById('txtPartNo'). To get this value, you will have to get it's client id which you can get using-
txtPartNo.ClientID so finally this will become-
data: "{'username':'" + document.getElementById('<%= txtPartno.ClientID %>').value + "'}",
If you don't try this way then you will not get the actual value of that textbox and undefined will be sent to the C# method which will not return anything.
First you should check if the JavaScript function it's getting called.
If it's getting called then you should check if the url is correct.
You can check in developer tools/ firebug etc. to see what request are you sending.
I did as follows:
ajaxCallSetting.js
var ajaxCallSetting = function (element, message, req) {
var baseInfo = {
baseUrl: "http://localhost:10266/"
};
var buildUrl= function() {
return baseInfo.baseUrl + message;
};
var callApi = function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: buildUrl(),
data: JSON.stringify(req),
dataType: "json"
}).success(function(data) {
response(data.d);
});
};
return {
init: function() {
$(element).autocomplete({
source: callApi
});
}
};
};
The head tag:
<head>
<title></title>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js" type="text/javascript"></script>
<script src="ajaxCallSetting.js"></script>
<link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet" />
<script type="text/javascript">
$(document).ready(function () {
var req = {
username: $('#txtPartno').val()
};
apiSettings('#txtPartno', "Default.aspx/GetAutoCompleteData", req).init();
});
</script>
</head>
As far as possible,
Keeping separate Html code with the code in JavaScript is useful.
I don't think your TextBox is being hooked up properly. Try this:
<asp:TextBox ID="txtPartno" CssClass="Textboxbase autosuggest" runat="server"></asp:TextBox>
And try this in your JavaScript:
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Inventory.aspx/GetAutoCompleteData",
data: "{'username':'" + request.term + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});

JS not working on click of an asp:Button

I have an array in JS and I am using following function to send it to aspx page
var array = [] //I want this array to be sent with JSON.
function result()
{
var jsonText = JSON.stringify({ list: array });
$.ajax({
type: "POST",
url: "test.aspx",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () { alert("it worked"); },
failure: function () { alert("Uh oh"); }
});
}
And I am calling it on click of a button in asp, like this:
<asp:Button id="submitbtn" runat="server" OnClick="Button1_Click" OnClientClick="result()" />
But it isn't working. So, whats the exact way to do it?
Please try below code it will work for you
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="demotest.aspx.cs" Inherits="Web.demotest" %>
<!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 src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
var array =[[48.154176701412744,11.551694869995117],[48.15131361676726,11.551694869995117],[48.15555092529958,11.549291610717773]]
function result() {
var jsonText = JSON.stringify({ list: array });
$.ajax({
url: "demotest.aspx/Demo", type: "POST", dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonText,
success: function (data) { alert("it worked"); },
error: function () { alert("Uh oh"); }
});
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button id="submitbtn" runat="server" Text="Ajax Call" OnClientClick="javascript:return result();" />
</div>
</form>
</body>
</html>
Write below code in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace Web
{
public partial class demotest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static void Demo(double[][] list)
{
//Write code here
}
}
}
For datatype use in c#.Please see the below picture

Passing javascript object to webservice via Jquery ajax

I have a webservice that returns an object
[WebMethod]
public List<User> ContractorApprovals()
I also have a webservice that accepcts an object
[WebMethod]
public bool SaveContractor(Object u)
When I make my webservice calls via Jquery:
function ServiceCall(method, parameters, onSucess, onFailure) {
var parms = "{" + (($.isArray(parameters)) ? parameters.join(',') : parameters) + "}"; // to json
$.ajax({
type: "POST",
url: "services/"+method,
data: parms,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (typeof onSucess == 'function' || typeof onSucess == 'object')
onSucess(msg.d);
},
error: function(msg, err) {
$("#dialog-error").dialog('open');}
});
I can call the first one just fine. My onSucess function gets passed a javascript object exactly structured like my User object on the service.
However, I am now having trouble getting the object back to the server.
I'm accepting Object as a parameter on the server side so I can't inagine there is an issue there. So I'm thinking something is wrong with the parms on the client side but i'm not sure what...
I am doing something to the effect
ServiceCall("AuthorizationManagerWorkManagement.asmx/ContractorApprovals",
"",
function(data,args){$("#div").data('user',data[0])},
null)
then
ServiceCall("AuthorizationManagerWorkManagement.asmx/SaveContractor",
JSON.stringify({u: $("#div").data("user")}) //dont work $("#div").data('user'), //These also do not work: "{'u': ' + $("#div").data("user") + '}", NOR JSON.stringify({u: userObject})
function(data,args){(alert(data)},
null)
I know the first service call works, I can get the data. The second one is causing the "onFailure" method to execute rather then "OnSuccess".
Any ideas?
UPDATE:
I chaed my last code block to use : JSON.stringify({u: $("#div").data("user")})
I now get Invalid object passed in, member name expected. (1):
But I have no idea what the means... Google has turned up plenty of that error, but no problem like mine...
ServiceCall("AuthorizationManagerWorkManagement.asmx/SaveContractor",
"{u: " + JSON.stringify($("#div").data("user")) + "}",
function(data, args) { alert(data); },
FailedServiceCall);
Ok I have posted the code as well as a link over Click here!
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">
var url = '<%=ResolveUrl("~/WebService.asmx/HelloWorld")%>';
$(document).ready(function() {
$('#txtAutoSuggest').keyup(function() {
var str = $("#txtAutoSuggest").val();
var a = JSON.stringify({ name: str });
CallService(a);
});
});
function CallService(a) {
$.ajax({
type: "POST",
url: url,
data: a,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status) {
$('#lblResult').text(data.d);
},
error: Error
});
}
function Error(request, status, error) {
$('#lblResult').text("Not Matched");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtAutoSuggest" runat="server"></asp:TextBox>
<asp:Label ID="lblResult" Text=" " Width="100%" runat="server" />
</div>
</form>
</body>
</html>
OR
application.js
var url = '<%=ResolveUrl("~/WebService.asmx/HelloWorld")%>';
$(document).ready(function() {
$('#txtAutoSuggest').keyup(function() {
var str = $("#txtAutoSuggest").val();
var a = JSON.stringify({ name: str });
CallService(a);
});
});
function CallService(a) {
$.ajax({
type: "POST",
url: url,
data: a,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status) {
$('#lblResult').text(data.d);
},
error: Error
});
}
function Error(request, status, error) {
$('#lblResult').text("Not Matched");
}
<%# WebService Language="C#" Class="WebService" %>
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX or JQuery.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
[WebMethod]
public string HelloWorld(string name)
{
Utility ut = new Utility(); // some class where you will have your database connection
ArrayList suggestedProblemName = ut.getItems(name); // some method of the class
return ""+suggestedProblemName[0];
}
}

Categories