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");
}
});
}
});
Related
I can't access webmethod within javascript. It gives the error in the title. Why might it be caused?
Js :
function funcGoster() {
$.ajax({
type: "POST",
url: "/WebService1.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// document.getElementById('text').innerHTML =
},
error: function (e) {
alert("başarısız" + e);
}
});
}
</script>
WebMethod :
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public static string HelloWorld()
{
return "Hello World";
}
}
Ok, what you have looks quite good, but note in the web service page, you have to un-comment the one line.
so, you should have this:
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
Ok, now our code and markup:
<asp:Button ID="Button1" runat="server" Text="Button" Width="153px"
OnClientClick="ajtest();return false;"/>
<br />
</div>
<script>
function ajtest() {
$.ajax({
type: "POST",
url: "/WebService1.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(' back from ajax message = ' + msg.d)
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage)
}
});
}
</script>
So, we also assume you have jQuery setup for this page? You need that.
You can call the web method without jQuery.
So, pure JavaScript, you could use this:
// Web method call without jQuery
function ajtest2() {
// ajax call without jquery
var xhr = new XMLHttpRequest()
xhr.open('POST', '/WebService1.asmx/HelloWorld')
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send('{}');
xhr.onload = function () {
if (xhr.status === 200) {
var userInfo = JSON.parse(xhr.responseText)
alert(' back form ajaxes message = ' + userInfo.d)
}
}
}
I am using Jquery to implement autocomplete to my textbox, i have used Ajax call,but my ajax url is not working.
When i inspect it is showing this error -> POST http://localhost:51444/Searchoperation/searchvalues 404 (Not Found)
My HTML and Script code
<script>
$('#myInput').keyup(function (event)
{
var searchname = $('#myInput').val()
$('#myInput').autocomplete(
{
scroll: true,
selectFirst: false,
autoFocus: false,
source: function(request, response)
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Searchoperation/searchvalues",
data: "{'Searchname':'" + searchname + "'}",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('/')[0],
val: item.split('/')[1]
}
}));
},
error: function (result) { }
});
},
select: function (event, ui) {
var vll = ui.item.val;
var sts = "no";
var url = 'search_app.aspx?prefix=' + searchname; // ur own conditions
$(location).attr('href', url);
}
})
})
</script>
<form autocomplete="off">
<div class="search-field" style="width:300px;">-->
<input id="myInput" type="text" name="myCountry" placeholder="SearchName" >
</div>
<input type="submit">
</form>
Code for fetching values from database
public List<string> searchvalues(string searchname)
{
try
{
List<string> result = new List<string>();
string connectionstring = #"Data Source=DESKTOP-LTV06QJ\SQLEXPRESS;Initial Catalog=Search;Integrated Security=True";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "connection_string";
conn.Open();
SqlCommand cmd = new SqlCommand("Sp_Search", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Emp_Name", searchname);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(string.Format("{0}/{1}", dr["Emp_id"], dr["Emp_Name"]));
}
conn.Close();
return result;
}
catch (Exception ex)
{
return null;
}
}
value entered in textbox is read but ajax call is not working.please help
try to use slash in the beginning of the path ("/Searchoperation/searchvalues"):
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Searchoperation/searchvalues",
data: "{'Searchname':'" + searchname + "'}",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('/')[0],
val: item.split('/')[1]
}
}));
},
....
You are missing page extension(.ASPX). Replace the ajax attribute URL like below,
url: "Searchoperation.aspx/searchvalues"
Also, make sure you have added [WebMethod] before the searchvalues method.
I hope this will help.
I can't for the life of me understand why this code isn't working. I need a second set of eyes to review it - TIA:
This function returns success, but the C# method is not called.
JavaScript
$(function() {
($("#survey").on("submit", function() {
var data = serializeForm();
$.ajax({
type: "POST",
url: "Default.aspx/SaveSurveyInfo",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert('ok');
},
error: function(data) {
alert('failed');
}
}); //ajax
return false;
}));
function serializeForm() {
var data = new Object;
$("#survey input[type='checkbox']").each(
function(index) {
data[$(this).get(0).id] = $(this).get(0).checked ? 1 : 0;
});
data.otherEnviron = $("#survey input[type='text']").val();
var strData = JSON.stringify(data);
return strData;
}
});
Revised:
$(function () {
($("#survey").on("submit", function() {
var data = serializeForm();
alert(data);
$.ajax({
type: "POST",
url: "Default.aspx/SaveSurveyInfo",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('ok-'+ data);
},
error: function (xml, textStatus, errorThrown) {
alert(xml.status + "||" + xml.responseText);
}
}); //ajax
return false;
}));
Note:
strData="{\"ms\":1,\"google\":0,\"PHP\":0,\"otherEnviron\":\".NET\"}"
C# WebMethod
[WebMethod]
private void SaveSurveyInfo(int ms, int google, int PHP, string otherEnviron)
{
using (SqlConnection scon = new SqlConnection(connectionString))
{
scon.Open();
SqlCommand scmd = scon.CreateCommand();
scmd.CommandType = System.Data.CommandType.StoredProcedure;
scmd.CommandText = "SurveyResults";
scmd.Parameters.AddWithValue("MicrosoftTranslator", ms);
scmd.Parameters.AddWithValue("GoogleTranslator", google);
scmd.Parameters.AddWithValue("PHPOkay", PHP);
scmd.Parameters.AddWithValue("other", otherEnviron);
scmd.ExecuteNonQuery();
}
}
Revised C#
[WebMethod]
public static void SaveSurveyInfo(int ms, int google, int PHP, string otherEnviron)
{
try
{
using (SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["C287577_NorthwindConnectionString"].ConnectionString))
{
scon.Open();
SqlCommand scmd = scon.CreateCommand();
scmd.CommandType = System.Data.CommandType.StoredProcedure;
scmd.CommandText = "SurveyResults";
scmd.Parameters.AddWithValue("MicrosoftTranslator", ms);
scmd.Parameters.AddWithValue("GoogleTranslator", google);
scmd.Parameters.AddWithValue("PHPOkay", PHP);
scmd.Parameters.AddWithValue("other", otherEnviron);
scmd.ExecuteNonQuery();
scmd.Dispose();
}
} catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
This is still not working. No error msg is shown, only ok.
because WebMethod must be public and static
Similar question: ASP.NET jQuery error: Unknown Web Method
If you need more security around your ajax call, try moving it to a web service.
public static void SaveSurveyInfo
The method should be static and public in aspx pages to be hit.
In asmx it can be just public.
I want to retrieve some data from Weather.asmx and wrote below code to get some data. There was no error from Javascript as I have seen but when the program runs it always go to groupPropertiesErrorHandler function. Any idea?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#butCallAjax').click(function() {
jQuery.support.cors = true;
$.ajax({
url: "http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP?ZIP=10007",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: groupPropertiesSuccessHandler,
error: groupPropertiesErrorHandler
});
});
function groupPropertiesSuccessHandler(data) {
var jsonObject = JSON.parse(data.body);
var properties = 'Group Properties:\n';
alert(properties);
}
// Error Handler
function groupPropertiesErrorHandler(data, errorCode, errorMessage) {
alert("Could not get the group properties: " + errorMessage);
}
});
</script>
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>