I'm trying to implement jquery - textbox autocomplete. for this setup a web service.
[WebMethod]
public List<Condition> GetCondition(string term)
{
List<Condition> listCondition = new List<Condition>();
string cs = ConfigurationManager.ConnectionStrings["db5"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spSelCondition", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#term",
Value = term
});
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
listCondition.Add(new Condition { ConditionID = rdr["ConditionID"].ToString(), ConditionName = rdr["ConditionName"].ToString() });
}
return listCondition;
}
}
public class Condition
{
public string ConditionName { get; set; }
public string ConditionID { get; set; }
}
WebService works perfectly fine. To populate the textbox with jquery autocomplete this javascript I've written.
<script type="text/javascript">
$(document).ready(function () {
$('#txtCondition').autocomplete({
source: function (request, response) {
$.ajax({
url: 'ibs_ws.asmx/GetCondition',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ term: request.term }),
dataType: 'json',
success: function (data) {
response(data.d);
},
error: function (err) {
alert(err);
}
});
}
});
})</script>
When I access the webservice it takes the #term as parameter and returns the result with ConditionID and ConditionName in xml formate. But on the webform when I give type anything in the textbox it alerts with [object object].
What could be the problem.
--
Thanks & Regards
May be it will help you. try this
I think you need to use $.map(data.d, function (value, key) {}). here is the example need to update your success code like below then you can get value inside object.
success: function (data) {
response($.map(data.d, function (value, key) {
return {
ConID: value.ConditionID,
ConNAme: value.ConditionName,
}
}))
},
AS you said your service returns conditionID and Name so i used these variable you can match what it returns exactly.
Related
I have a text box that I am trying to have autocomplete with values from a database. The code is, however, not doing anything when I begin typing in the text box. Does anyone have any idea how to fix this? The Scripts are in the head of the page.
<asp:TextBox placeholder="Search by job title" runat="server" CssClass="search" ID="searchTitle"></asp:TextBox>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<script>
$(function () {
$("#searchTitle").autocomplete({
source: function (request,response) {
var param = { posting_jobPosition: $("#searchTitle").val() };
$.ajax({
url: "jobseekerHome.aspx/GetTitles",
data: JSON.stringify(param),
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 }}))
},
});
},
minlength: 1
});
});
</script>
[WebMethod]
public static List<string> GetTitles(string posting_jobPosition)
{
string CS = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
OleDbConnection Connection = new OleDbConnection(CS);
List<string> Titles = new List<string>();
string query = string.Format("SELECT posting_jobPosition FROM BusinessJobPosting WHERE (posting_jobPosition LIKE '%{0}%' AND isActive = true)", posting_jobPosition);
OleDbCommand oleCom1 = new OleDbCommand(query, Connection);
Connection.Open();
OleDbDataReader reader = oleCom1.ExecuteReader();
while (reader.Read())
{
Titles.Add(reader[0].ToString());
}
Connection.Close();
return Titles;
}
Thanks guys :)
One possible reason that I see is the ID. Change the id as:
$("#<%=searchTitle.ClientID%>").autocomplete({
related: Accessing control client name and not ID in ASP.NET
I am trying to retrieve a list from C# code to an aspx page using ajax.
this is the ajax function:
$.ajax({
type: 'POST',
url: 'admin.aspx/getGenderCount',
contentType: 'application/json',
dataType: 'json',
data: '{}',
success: successRetireveGenders,
failure: function (response) {
alert("Error");
}
});
function successRetireveGenders(dataValues) {
alert(dataValues); // displayed [object object]
// but i actually have 2 rows result
alert(dataValues.data); //alert with "undefined"
alert(dataValues.d); //alert with "undefined"
// i try to put loop from 0 to response.d.length
for (var i = 0; i < dataValues.length; i++) {
alert(dataValues.length); //alert with "undefined"
alert(dataValues.d.length); //alert with "undefined"
}
I am always seeing an alert with message:
undefined
c# code:
[System.Web.Services.WebMethod]
public static List<ParticipantGender> getGenderCount()
{
List<ParticipantGender> ListOfParticipantGender = new List<ParticipantGender>();
var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand("getGenderCount", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
while (rdr.Read())
{
ListOfParticipantGender.Add(
new ParticipantGender
{
cnt = rdr.GetValue(0).ToString(),
gender = rdr.GetValue(1).ToString(),
});
}
return ListOfParticipantGender;
}
ParticipantGender class:
public class ParticipantGender
{
public string gender;
public string cnt;
public ParticipantGender()
{
//
// TODO: Add constructor logic here
//
}
public ParticipantGender(string gender, string cnt)
{
this.gender = gender;
this.cnt = cnt;
}
}
EDIT:
$.ajax({
type: 'POST',
url: 'admin.aspx/getGenderCount',
contentType: 'application/json',
dataType: 'json',
data: '{}',
success: callback,
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
var callback = function (data, textStatus, xhr) {
alert("hi"); // not alerted
alert(data + "\t" + textStatus); // not alerted
};
EDIT:
i got in the console:
jsapi:23 A parser-blocking, cross site (i.e. different eTLD+1) script,
https://www.google.com/uds/?file=visualization&v=1&packages=corechart,
is invoked via document.write. The network request for this script MAY
be blocked by the browser in this or a future page load due to poor
network connectivity. If blocked in this page load, it will be
confirmed in a subsequent console message. See
https://www.chromestatus.com/feature/5718547946799104 for more
details. google.loader.f # jsapi:23 jsapi:23 A parser-blocking, cross
site (i.e. different eTLD+1) script,
https://www.google.com/uds/api/visualization/1.0/40ff64b1d9d6b3213524485974f36cc0/format+en,default+en,ui+en,corechart+en.I.js,
is invoked via document.write. The network request for this script MAY
be blocked by the browser in this or a future page load due to poor
network connectivity. If blocked in this page load, it will be
confirmed in a subsequent console message. See
https://www.chromestatus.com/feature/5718547946799104 for more
details. google.loader.f # jsapi:23 fontawesome-webfont.woff2:1 Failed
to load resource: the server responded with a status of 404 (Not
Found)
You should serialize the List<ParticipantGender> to JSON. You can install package Newtonsoft.Json which provides a lot of features.
For your case
using System.Configuration;
using Newtonsoft.Json;
[System.Web.Services.WebMethod]
public static string getGenderCount()
{
var connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var ListOfParticipantGender = new List<ParticipantGender>();
using(var conn = new SqlConnection(connStr))
{
conn.Open();
using(var cmd = new SqlCommand("getGenderCount", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
using(var rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
while (rdr.Read()) {
ListOfParticipantGender.Add(
new ParticipantGender
{
cnt = rdr.GetValue(0).ToString(),
gender = rdr.GetValue(1).ToString(),
}
);
}
}
}
}
}
var json = JsonConvert.SerializeObject(ListOfParticipantGender);
return json;
}
Define the Callback function with necessary parameters and assign it to the $.ajax success event.
Also, there is no such event failure for $.ajax instead use error
var callback = function(data, textStatus, xhr)
{
alert(data + "\t" + textStatus);
};
Assign this callback to the success event
$.ajax({
type: 'POST',
url: 'admin.aspx/getGenderCount',
contentType: 'application/json',
dataType: 'json',
data: {},
success: callback,
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
This is a WebMethod that takes value from front-end in the lvl string.
Later that string is checked through getDuplicate procedure if there is already that value in the database. If the value exists then the insert procedure InsertObject is not activated and if there is no such value in the database first procedure returns null and the insert procedure will work.
Everything work well in the code all I need is some kind of an alert message from the C# part of the code if the insert is a success, and if it fails.
I tried so many examples and I can't find any solution :/
Can someone please help ?
[WebMethod(EnableSession = true)]
public static void GetCollection(string lvl)
{
string conn = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conn))
try
{
connection.Open();
SqlCommand cmdCount = new SqlCommand("getDuplicate", connection);
cmdCount.CommandType = CommandType.StoredProcedure;
cmdCount.Parameters.AddWithValue("#ObjekatName", lvl);
var count = (string)cmdCount.ExecuteScalar();
if (count == null)
{
SqlCommand cmdProc = new SqlCommand("InsertObjekat", connection);
cmdProc.CommandType = CommandType.StoredProcedure;
cmdProc.Parameters.AddWithValue("#ObjekatName", lvl);
cmdProc.ExecuteNonQuery();
//successful alert
}
else
{
//fail alert
}
}
catch
{
}
finally
{
connection.Close();
}
return;
}
Update:
Ajax that sends values to the method:
$(function () {
$('#myButton').on('click', function () {
var lvl = $('#MainContent_txtProductConstruction').val()
$.ajax({
type: "POST",
url: "NewProductConstruction.aspx/GetCollection",
data: JSON.stringify({'lvl': lvl }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Saved successfully.");
console.log(response);
location.reload(true);
},
error: function (response) {
alert("Not Saved!");
console.log(response);
location.reload(true);
}
});
});
});
You can return a json object. Change the return type of method as string.Include using Newtonsoft.Json; and then when you want to return, create an object like this:
[WebMethod]
public static string GetCollection(string lvl)
{
bool isInserted = false;
// set the value of isInserted
// you can send code a numeric value or bool value according to your need
var result = new {code = isInserted, message = isInserted ? "Succesfully inserted" : "Already Exists"};
return JsonConvert.SerializeObject(result);
}
At the client side, check the response
success: function (response) {
console.log(response);
if(response != null){
var data = $.parseJSON(response)
alert(data.message)
}
location.reload(true);
}
Hi I am developing one small application in sharepoint 2013 webparts. I am trying to bind dropdown from database using angular js. My pages are RFRegretLetterWP.ascx and RFRegretLetterWP.ascx. I have tried as below.
<script type="text/javascript">
angular.module('drpdwnApp', []).controller('drpdwnCtrl', function ($scope, $http) {
$scope.ProductList = null;
//Declaring the function to load data from database
$scope.fillProductList = function () {
$http({
method: 'POST',
url: 'RFPRegretLetterWP.ascx/GetDDLNames',
data: {}
}).success(function (result) {
$scope.ProductList = result.d;
});
};
//Calling the function to load the data on pageload
$scope.fillProductList();
});
</script>
This is my html code.
<div ng-app="drpdwnApp" ng-controller="drpdwnCtrl">
<select ng-model="drpdpwnvalue" ng-options="item.OrderID for item in ProductList">
<option value="" label="Select and item"></option>
</select>
</div>
This is my server side code.
public static List<OrderList> GetDDLNames()
{
List<OrderList> list = new List<OrderList>();
using (SqlConnection conn = new SqlConnection("I have connection string here"))
{
conn.Open();
string strquery = ("select * from CategoryMaster order by CategoryName Asc");
using (SqlCommand cmd = new SqlCommand(strquery, conn))
{
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
OrderList objorder = new OrderList(reader["Vendor_ID"].ToString());
list.Add(objorder);
}
}
}
return list;
}
public class OrderList
{
public string Vendor_ID;
public OrderList(string UName)
{
Vendor_ID = UName;
}
}
I have little doubt in making call to server. This is my Url
url: 'RFPRegretLetterWP.ascx/GetDDLNames' but my page name is RFPRegretLetterWP.ascx.cs so i am having confusion. In some articles i noticed [System.Web.Services.WebMethod()] but when i put it it gives me error. May I have some suggestions on this regards. thank you for consideration
I suggest you to insert the server side code into a LayoutsPage like this:
using System.Web.Services;
public partial class RFPRegretLetterWP : LayoutsPageBase
{
[WebMethod]
public static IEnumerable GetDDLNames()
{
List<OrderList> list = new List<OrderList>();
/* your code */
return list;
}
public class OrderList
{
/* your code */
}
}
and call the web method with the url:
_spPageContextInfo.webAbsoluteUrl/_layouts/15/<project name>/<pagename>.aspx/GetDDLNames
like this:
<script type="text/javascript">
angular.module('drpdwnApp', []).controller('drpdwnCtrl', function ($scope, $http) {
$scope.ProductList = null;
//Declaring the function to load data from database
$scope.fillProductList = function () {
$.ajax({
type: "POST",
url: _spPageContextInfo.webAbsoluteUrl + "/_layouts/15/<project name>/RFPRegretLetterWP.aspx/GetDDLNames",
data: null,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: onCompleted,
error: onError
});
function onCompleted(data) {
if (data !== null)
$scope.ProductList = data.d;
}
function onError(error) {
console.log('An error has occurred: ' + error.data);
}
};
//Calling the function to load the data on pageload
$scope.fillProductList();
});
</script>
Replace <project name> with your visual studio project's name.
I have seen several questions around this topic on here, but can't seem to get my fullcalendar to display properly using the provided methods, so I was hoping someone could give me a hand with fixing my issue.
My JSON feed seems to populate correctly, although I see some saying that it only works with single quote, and others only work with double quotes. (possibly an issue with the double quotes surrounding the whole feed?)
"[{"title":"change1","start":"2016-10-17T10:00:00","end":"2016-10-17T12:00:00","allDay":false},{"title":"change2","start":"2016-10-18T10:00:00","end":"2016-10-18T12:00:00","allDay":true},{"title":"change3","start":"2016-10-19T10:00:00","end":"2016-10-19T12:00:00","allDay":false}]"
calendar.aspx.cs:
public class Event
{
public string title;
public string start;
public string end;
public bool allDay;
}
[WebMethod]
public static string GetEvents()
{
var events = new List<Event>();
var sqlQuery = "SELECT title, starttime, endtime, allDay FROM [DeploymentDashboard].[dbo].[ChangeCalendar]";
using (var sqlConnection = new SqlConnection("Data Source=*server*;Initial Catalog=DeploymentDashboard;Integrated Security=True;"))
{
using (var cmd = new SqlCommand(sqlQuery, sqlConnection))
{
sqlConnection.Open();
using (var reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
events.Add(new Event()
{
start = DateTime.Parse(reader["starttime"].ToString()).ToString("s"),
end = DateTime.Parse(reader["endtime"].ToString()).ToString("s"),
title = reader["title"].ToString(),
allDay = (bool)reader["allDay"]
});
}
}
}
sqlConnection.Close();
}
}
var theSerializer = new JavaScriptSerializer();
return theSerializer.Serialize(events);
}
calendar.aspx:
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "calendar.aspx/GetEvents",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
$('#calendar2').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: data.d
});
});
});
</script>
Try this:
var eventsArray = [{"title":"change1","start":"2016-10-17T10:00:00","end":"2016-10-17T12:00:00","allDay":false},{"title":"change2","start":"2016-10-18T10:00:00","end":"2016-10-18T12:00:00","allDay":true},{"title":"change3","start":"2016-10-19T10:00:00","end":"2016-10-19T12:00:00","allDay":false}]
$('#calendar2').fullCalendar({
events: eventsArray
});
This should fix it.
events: JSON.parse(data.d);
This helped: https://www.w3schools.com/js/js_json_parse.asp
Imagine we received this text from a web server:
'{ "name":"John", "age":30, "city":"New York"}'
Use the JavaScript function JSON.parse() to convert text into a
JavaScript object:
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');