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;
}
Related
I keep receiving the undefined error. Here is the ajax method.
function testing() {
var data = JSON.stringify(
{
"TestID1": "12345",
"TestID2": "12345",
"TestID3": "12345",
});
$.ajax({
type: "POST",
url: "Test.ashx",
data: data,
//async: false,
//cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.ID);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
}
});
}
Here is the controller/handler.
public void ProcessRequest(HttpContext context)
{
string jsonString = String.Empty;
HttpContext.Current.Request.InputStream.Position = 0;
using (StreamReader inputStream = new StreamReader(HttpContext.Current.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
JavaScriptSerializer jSerialize = new JavaScriptSerializer();
var receipt = jSerialize.Deserialize<Receipt>(jsonString);
if (receipt != null)
{
InsertData(receipt.TestID1, receipt.TestID1, receipt.TestID1);
var wrapper = new { ID = receipt.TestID1};
context.Response.Write(JsonConvert.SerializeObject(wrapper));
//context.Response.Write("{ \"data\": [1,2,3] }");
//context.Response.End();
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
Right now I am getting undefined error, but I was getting the "JSON.parse: unexpected end of data at line 1 column 1 of the JSON data" until recently. The data that is being posted is working since the InsertData() function inserts the correct data. I also tried setting the async function in the ajax method to false, but no luck. Also, tried sending specific responses (like the one commented out) and so far none have succeeded.
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 have below code in C# which adds data in Dictionary
public static Dictionary<int, string> ReadFile()
{
Dictionary<int, string> datalist = new Dictionary<int,string>();
var lines = File.ReadAllLines(#"C:\\temp\\Sample.txt");
int i = 1;
foreach (var line in lines)
{
datalist.Add(i, line);
i++;
}
return datalist;
}
Now, I want to display Dictionary data separated by key line by line in textarea. Below is my UI code
<button type="button" id ="GetFlatFile">Click Me!</button>
<div id ="DisplayFlatFile">
</div>
function GetFlatFileAndSetupColumn() {
$("#GetFlatFile").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/ReadFile",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (jsondata) {
mydata = jsondata.d;
$('#DisplayFlatFile').empty();
$('#DisplayFlatFile').append(mydata);
}, error: function (x, e) {
alert("The call to the server side failed. " + x.responseText);
}
});
});
}
How to do it?
First, GetFlatFile is not a <textarea> element, it's <div> element. Assumed that jsondata.d contains dictionary values returned from code-behind method, you can use jQuery.each() to iterate values:
function GetFlatFileAndSetupColumn() {
$("#GetFlatFile").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/ReadFile",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (jsondata) {
mydata = jsondata.d;
$('#DisplayFlatFile').empty();
// iterate keys and values here
$(mydata).each(function (key, value) {
// data display example
$('#DisplayFlatFile').append(key + ' - ' + value);
// line break per iteration
$('#DisplayFlatFile').append('<br />');
});
}, error: function (x, e) {
alert("The call to the server side failed. " + x.responseText);
}
});
});
}
Additionally, your code-behind method should be marked with [WebMethod] attribute :
[WebMethod]
public static Dictionary<int, string> ReadFile()
{
Dictionary<int, string> datalist = new Dictionary<int, string>();
var lines = File.ReadAllLines(#"C:\\temp\\Sample.txt");
int i = 1;
foreach (var line in lines)
{
datalist.Add(i, line);
i++;
}
return datalist;
}
Related issue:
How to get data from C# WebMethod as Dictionary<> and display response using jquery ajax?
trying to retrieve data from data.d but not able to access data from data.d as it says data.d is undefined
this is my jquery function
$("body").on("click", "#aProfile", function () {
$("#divProfile").show();
$("#divChangePassword").hide();
$("#txtProfileUserName").val('<%=HttpContext.Current.Session["UserName"].ToString()%>').prop('disabled', true);
var UserName = $("#txtProfileUserName").val();
$.ajax({
type: "POST",
url: "StudentPanel.aspx/GetUserDetails",
data: JSON.stringify({ UserName: $('#txtProfileUserName').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
alert(data.d);
$('#txtProfileName').val(data.d.Name);
$('#txtProfileEmail').val(data.d.Email);
$('#txtProfileGender').val(data.d.Gender);
$('#txtProfileContact').val(data.d.Contact);
$('#txtProfileCountry').val(data.d.Country);
$('#txtProfileState').val(data.d.State);
$('#txtProfileCity').val(data.d.City);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
$('#txtProfileCountry').prop('visible', false);
$(".Profile").prop('disabled', true);
});
this is my c# function
[System.Web.Services.WebMethod]
public static User GetUserDetails(string UserName){
User u = new User();
string CS = ConfigurationManager.ConnectionStrings["BBCS"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS)){
SqlCommand cmd = new SqlCommand("spGetSISUserByName",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#UserName",
Value = UserName
});
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
u.Name = dr["Name"].ToString();
u.UserName = UserName;
u.Email = dr["Email"].ToString();
u.Gender = dr["Gender"].ToString();
u.Contact = dr["Contact"].ToString();
u.Country = dr["Country"].ToString();
u.State = dr["State"].ToString();
u.City = dr["City"].ToString();
}
}
return u;
}
I want to assign value from data.d but it returns undefined data.d
Problem solved
Inside ~/App_Start/RouteConfig.cs I changd :
settings.AutoRedirectMode = RedirectMode.Permanent;
To:
settings.AutoRedirectMode = RedirectMode.Off;
or you can just comment the line and its done
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.