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.
Related
I have following the Ajax call method and The asp.net web method.
My asp.net function is returning some values I need those back in Ajax call.
I have tried a lot of things but not succeeded yet.
here is my function, I need to convert my list to JSON:
public List < Node > ReadData() {
SqlConnection conn = new SqlConnection("Data Source=OUMAIMA-PC\\SQLEXPRESS;Initial Catalog=AGIRH;Integrated Security=True");
string query = "SELECT uo,uo_rattachement,lib_reduit FROM UNITE_ORG ";
List < Node > list = new List < Node > ();
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read()) {
list.Add(new Node {
uo = dataReader.GetString(0),
uo_rattachement = dataReader.GetString(1),
lib_reduit = dataReader.GetString(2)
});
}
dataReader.Close();
conn.Close();
return list;
}
**Jquery:**
$(function() {
$.ajax({
type: "POST",
url: 'WebForm1.aspx.cs/ReadData',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response) {
if (response != null && response.d != null) {
var data = response.d;
alert(typeof(data));
data = $.parseJSON(data);
alert(data.subject);
alert(data.description);
}
}
}; $.ajax(options);
});
});
here is my source code, i us webforms Application and orgchart.js liberary
this aspx.cs source code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace testProjet
{
public partial class WebForm1 : System.Web.UI.Page
{
private object JsonConvert;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["Nodes"] == null)
{
var jsonSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Node> list = new List<Node>();
list.Add(new Node
{
uo = "1",
lib_reduit = "Name 1"
});
Session["Nodes"] = jsonSerialization.Serialize(list);
}
}
}
public static List<Node> ReadData()
{
SqlConnection conn = new SqlConnection("Data Source=OUMAIMA-PC\\SQLEXPRESS;Initial Catalog=AGIRH;Integrated Security=True");
string query = "SELECT uo,uo_rattachement,lib_reduit FROM UNITE_ORG ";
List<Node> list = new List<Node>();
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
list.Add(new Node
{
uo = dataReader.GetString(0),
uo_rattachement = dataReader.GetString(1),
lib_reduit = dataReader.GetString(2)
});
}
dataReader.Close();
conn.Close();
return list;
}
public static void Add(string uo, string uo_rattachement, string lib_reduit)
{
var jsonSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();
var list = jsonSerialization.Deserialize<List<Node>>((string)HttpContext.Current.Session["Nodes"]);
list.Add(new Node
{
uo = uo,
uo_rattachement = uo_rattachement,
lib_reduit = lib_reduit
});
HttpContext.Current.Session["Nodes"] = jsonSerialization.Serialize(list);
}
public static void Remove(string uo)
{
var jsonSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();
var list = jsonSerialization.Deserialize<List<Node>>((string)HttpContext.Current.Session["Nodes"]);
Node removeItem = null;
foreach (var item in list)
{
if (item.uo == uo)
{
removeItem = item;
break;
}
}
list.Remove(removeItem);
HttpContext.Current.Session["Nodes"] = jsonSerialization.Serialize(list);
}
public static void Update(Node oldNode, Node newNode)
{
var jsonSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();
var list = jsonSerialization.Deserialize<List<Node>>((string)HttpContext.Current.Session["Nodes"]);
foreach (var item in list)
{
if (item.uo == newNode.uo)
{
item.uo_rattachement = newNode.uo_rattachement;
item.lib_reduit = newNode.lib_reduit;
break;
}
}
HttpContext.Current.Session["Nodes"] = jsonSerialization.Serialize(list);
}
}
}
and this is my aspc code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="testProjet.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title> OrgChart</title>
<script src="OrgChart.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<style>
html, body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
overflow: hidden;
}
#tree {
width: 100%;
height: 100%;
}
.field_0 {
font-family: Impact;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true" />
<div id="tree">
</div>
</form>
<script >
var chart = new OrgChart(document.getElementById("tree"), {
nodeBinding: {
field_0: "UO",
field_1:"Uo_Rattachement"
},
menu: {
pdf: { text: "Export PDF" },
png: { text: "Export PNG" },
svg: { text: "Export SVG" },
csv: { text: "Export CSV" }
},
nodeContextMenu: {
edit: { text: "Edit", icon: OrgChart.icon.edit(18, 18, '#039BE5') },
add: { text: "Add", icon: OrgChart.icon.add(18, 18, '#FF8304') }
},
nodeMenu: {
details: { text: "Details" },
edit: { text: "Edit" },
add: { text: "Add" },
remove: { text: "Remove" }
}
});
$.ajax({
type: "POST",
url: 'WebForm1.aspx.cs/ReadData',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response != null && response.d != null) {
var data = response.d;//this data already json you can iterate with each
$.each(data, function (index, node) {
console.log(node);
});
};
chart.on('add', function (sender, n) {
$.ajax({
type: 'POST',
url: '<%= ResolveUrl("WebForm1.aspx.cs/Add") %>',
data: JSON.stringify(n),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
});
chart.on('remove', function (sender, uo) {
$.ajax({
type: 'POST',
url: '<%= ResolveUrl("WebForm1.aspx.cs/Remove") %>',
data: JSON.stringify({ uo: uo }),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
});
chart.on('update', function (sender, oldNode, newNode) {
$.ajax({
type: 'POST',
url: '<%= ResolveUrl("WebForm1.aspx.cs/Update") %>',
data: JSON.stringify({ oldNode: oldNode, newNode: newNode }),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
});
chart.load(<%= Session["Nodes"] %>);
});
</script>
<select style="position: absolute;right: 90px;top: 30px;color: #7a7a7a;font-size: 14px;padding: 10px;background-color: #F57C00;color: #ffffff;width: 100px;z-index:2;" id="selectTemplate">
<option>luba</option>
<option>olivia</option>
<option>derek</option>
<option>diva</option>
<option>mila</option>
<option>polina</option>
<option>mery</option>
<option>rony</option>
<option>belinda</option>
<option>ula</option>
<option>ana</option>
<option>isla</option>
<option>deborah</option>
</select>
</body>
</html>
First you should make function static and add WebMethod attribute:
[WebMethod()]
public static List<Node> ReadData()
{
//..
}
Then you don't need to convert response to JSON beacuse data is already JSON. You can directly use it as following:
$.ajax({
type: "POST",
url: 'WebForm1.aspx/ReadData',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response) {
if (response != null && response.d != null) {
var data = response.d;//this data already is json which represent list of Node so that you can iterate with each
$.each(data, function (index, node) {
console.log(node);
});
}
}
};
In addition url must be WebForm1.aspx/ReadData instead of WebForm1.aspx.cs/ReadData
Change the method's return type to JsonResult and return new Json object with subject and desription.
public JsonResult ReadData() {
// Rest of your code
return Json(new { data = list, subject = "My subject", description = "My Description" });
}
Jquery:
$(function () {
$.ajax({
type: "POST",
url: 'Home/ReadData',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response != null && response.data != null) {
var data = response.data;
alert(typeof (data));
alert('subject: ' + response.subject);
alert('description: ' + response.description);
}
}
})
});
Autocomplete TextBox code in JavaScript
function getList_FixedValue() {
var arr = ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"];
return arr;
}
function getList_FromServerSide() {
$.ajax({
type: "POST",
url: "patient-problem-submit.aspx/GetCCList",
data: '{doctorId: "' + $("#<%=hdnDoctorId.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d); //here alert shows my expected data
return response.d;
},
failure: function (response) {
alert("failed to get data");
}
});
}
$('#txtCCPick').autocompleteArray(
//getList_FixedValue(), //this works fine
getList_FromServerSide(), //this not working
{
delay: 10,
minChars: 1,
matchSubset: 1,
onItemSelect: selectItem,
onFindValue: findValue,
autoFill: true,
maxItemsToShow: 10
}
);
});
WebMethod in VB.......
<System.Web.Services.WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Shared Function GetCCList(ByVal doctorId As String) As String()
Dim customers As New List(Of String)()
Using conn As New SqlConnection()
conn.ConnectionString = ConfigurationManager.ConnectionStrings("ConnStr").ConnectionString
Using cmd As New SqlCommand()
cmd.CommandText = String.Format("SELECT pkCCID, CCName FROM CC WHERE fkDoctorID = " + doctorId + " order by CCName")
cmd.CommandType = CommandType.Text
'cmd.Parameters.AddWithValue("#DoctorId", doctorId)
cmd.Connection = conn
conn.Open()
Dim dbAdpt As New SqlDataAdapter(cmd)
Dim ds As New DataSet
dbAdpt.Fill(ds)
If (Not ds Is Nothing) Then
If (ds.Tables(0).Rows.Count > 0) Then
For Each row As DataRow In ds.Tables(0).Rows
customers.Add(String.Format("{0}", row("CCName")))
Next
End If
End If
conn.Close()
End Using
End Using
Return customers.ToArray()
End Function
Inside autocompleteArray, When I call getList_FixedValue() function then items are loaded my textbox properly. but when I call getList_FromServerSide() function then items are not loaded in my textbox. So i need help for this issue. thanks in advance.
Ultimately I got my solution by the following way. problem was that there are no direct return option from success portion of ajax call
function getList_FromServerSide() {
var result;
$.ajax({
type: "POST",
url: "patient-problem-submit.aspx/GetCCList",
data: '{doctorId: "' + $("#<%=hdnDoctorId.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: !1,
success: function (response) {
//alert(response.d); //here alert shows my expected data
result = response.d;
},
failure: function (response) {
alert("failed to get data");
}
});
return result;
}
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.
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");
}
});
}
});
I am new working with jquery ajax calls in fact my first time and, I am running into a issue here my web service is working but for some reason when I try to call it from jquery ajax the data is not retrieve.
Please I've been working the whole day on this and I need to finish it tonight.
My web method is this :
public Didyoumean SayHello(string search)
{
Didyoumean Didyoumean = new Didyoumean();
string cs = ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString;
using(SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand ("USP_DidYouMean",con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter("#search",search);
cmd.Parameters.Add(parameter);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Didyoumean.SearchInput = reader["detail"].ToString();
}
reader.Close();
con.Close();
}
return Didyoumean;
}
my Didyoumean class is this:
public class Didyoumean
{
public string SearchInput { get; set; }
}
my ajax call is this (the error is most likely to be here)
function bla() {
var SearchInput = document.getElementById("#locationSearchInput").value;
var DataObject = { search: SearchInput };
$.ajax({
type: "POST",
url: "/kiosk/EmailCoupon.asmx/SayHello",
data: JSON.stringify({dataObject}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('.tags_select a').html(data.d);
},
error: function () {
$('.tags_select a').html("<p>no suggestion</p>")
}
});
}
and finally my html
<input id="Button1" type="button" value="button" onclick="bla()"/>
<div class="tags_select">
Basically what I am trying to do is depending on the data in my database the application give suggestions for spelling errors.
note: do not pay attention to the name of the functions and methods this is just a test.
Your service might be like this
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public Didyoumean SayHello(string search)
{
Didyoumean didyoumean = new Didyoumean();
didyoumean.searchInput = "result of " + search;
return didyoumean;
}
}
and your javascript is
function test() {
var SearchInput = "test";
$.ajax({
type: "POST",
url: "/WebService1.asmx/SayHello",
data: JSON.stringify({search:SearchInput}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var didYouMean = data.d;
alert(didYouMean.searchInput);
},
error: function (e) {
console.log(e);
}
});
}