I try using jQuery tokenize2 with asp.net/C#, I try to get suggestions from ajax. When I try to inspect, firebug or visual studio, there is no error, but the tokenize2 not working.
here are the code:
Webservice:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetRelated(string search)
{
SearchEntity[] arrEnt = new SearchEntity[]
{
new SearchEntity()
{
Value = "value 1",
Text = "text 1"
},
new SearchEntity()
{
Value = "value 2",
Text = "text 2"
}
};
return JsonConvert.SerializeObject(arrEnt, Newtonsoft.Json.Formatting.Indented);
}
Javacript:
<script>
$(document).ready(function () {
$('.autoCom').tokenize2({
dataSource: function(term, object) {
$.ajax('GetData.asmx/GetRelated', {
data: { search: term, start: 0 },
dataType: 'json',
success: function(data) {
var $items = [];
$.each(data, function(k, v) {
$items.push(v);
});
object.trigger('tokenize:dropdown:fill', [$items]);
}
});
}
});
});
</script>
Please tell me, is there something wrong with the code?
Related
I have a problem displaying the data in the dropdown list using select2. I think the reason is the Query returning many rows. when I limit the number of Row to 50 (where Rownum <=100 ) the data displayed but when I remove the where condition no data display. The PatientDemo table has more than 600000 rows Any help how to solve this issue. I am using Orcale and C#
View
<link href="~/Content/css/select2.min.css" rel="stylesheet" />
<div class="jumbotron">
<input type="hidden" id="textBoxVal" />
<select class="mySelect2" style="width:500px;">
</select>
</div>
<script>
$(document).ready(function () {
$(".mySelect2").select2({
placeholder: "Select category",
allowClear: true,
theme: "classic",
ajax: {
url: "/Home/GetCategory",
dataType: 'json',
delay: 10000,
data: function (params) {
return {
searchTerm: params.term
};
},
processResults: function (data, params) {
return {
results: data
};
}
}
});
});
$(".mySelect2").on("change", function () {
var catId = $(this).val();
$("#textBoxVal").val(catId);
var textBoxValueData = $("#textBoxVal").val();
$.ajax({
url: '/Home/Save?data=' + textBoxValueData,
dataType: 'json',
type: 'post',
});
});
Model
public class Select2Model
{
public string id { get; set; }
public string text { get; set; }
}
C#
public JsonResult GetCategory(string searchTerm)
{
var list = new List<Select2Model>();
using (OracleConnection conn = new OracleConnection(WebConfigurationManager.ConnectionStrings["PatientRecord"].ConnectionString))
{
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = #"SELECT PATIENT, NAMEFORWARD FROM PATIENTDEMO ";
cmd.CommandType = CommandType.Text;
OracleDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
list.Add(new Select2Model()
{
text = rdr["NAMEFORWARD"].ToString(),
id = rdr["Patient"].ToString()
});
}
var dataList = list.ToList();
if (searchTerm != null)
{
dataList = list.Where(x => x.text.Contains(searchTerm)).ToList();
}
var modifiedData = dataList.Select(x => new {
id = x.id,
text = x.text
});
return Json(modifiedData, JsonRequestBehavior.AllowGet);
}
}
public JsonResult Save(string data)
{
return Json(0, JsonRequestBehavior.AllowGet);
}
600000 rows in a drop down list is not a user friendly one. Instead why don't you implement a drop down list with auto complete?
Check the example at the bottom of this page: https://api.jqueryui.com/autocomplete/
Update:
In your case you source would be a ajax call to the server side to pull the relevant data. Like this:
$('#myautocomplete').autocomplete({
type: "POST",
minLength: 3,
source : function (request, response)
{
var source_url = "../handlers/MyLookup.ashx?someparameter=" + $("#someparameter").val();
$.ajax({
url: source_url,
dataType: "json",
data: request,
success: function (data) { response(data); },
error : function (a,b,c) { HandleLookUpError(a); }
});
},
select: function (event, ui) { $('#result').val(ui.item.id); }
});
Note the source_url variable and the ajax call in the above code.
More details on how to load data from server side is here: https://stackoverflow.com/a/8873641/218408
I want to be able to return json object with a custom error/success message using the same line of code on post request: i have these two lines of code:
return Json(data);
return Json(new { f = "error" });
I want to be able display it in one line like this:
return Json(data, Json(new { f = "error" }));
I know i can't have multiple return statements in my code. but i want to return the data with message.
My ServerSide Code:
if (getId > 0)
{
var getList = appointmentRepository.GetAppointmentList(userId);
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList);
return Json(data);
return Json(new { s = "success" });
}
else
{
var getList = appointmentRepository.GetAppointmentList(userId);
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList);
return Json(data);
return Json(new { f = "error" });
}
My Ajax Fucntion:
<script type = "text/javascript">
$(document).ready(function () {
$('#tblAppointment').DataTable({
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
});
var table = $("#tblAppointment").DataTable();
$("#saveButton").click(function () {
console.log("appDate:" + $('.datetimepicker').val());
$.ajax({
url: '/Appointment/InsertPatientAppointment/',
type: "POST",
data: JSON.stringify({
appointmentDate: $(".datetimepicker").val(),
patientRegNo: $("#patientRegNo").val(),
reasons: $("#reasons").val()
}),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (_data) {
if (_data.f !== undefined) {
swal({
title: "Failed!",
text: _data.f, //"Ooops! something went wrong,
record not saved,
try again later ",
type: "info"
});
table.clear().draw();
//table.destroy();
// $("#viewReportBtn").prop("disabled", false);
return false;
} else {
swal({
title: "Success!",
text: _data.s, //"Appointment added successfully!",
type: "success"
});
}
$(".datetimepicker").val('');
$("#patientRegNo").val('');
$("#reasons").val('');
var arr = $.map(JSON.parse(_data), function (el) {
return
el
});
if (arr.length === 0) {
swal({
title: "No Record Found!",
text: _data.f, //"Your search returns an empty
result set !",
type: "info"
});
table.clear().draw();
return false;
}
table.clear();
table.destroy();
$('#tblAppointment').dataTable({
data: arr,
columns: [{
"data": "MatricRegNo"
},
{
"data": "PatientName"
},
{
"data": "EntryDate"
},
{
"data": "AppointmentDate"
},
{
"data": "Reasons"
},
{
"data": function (data, type, row, meta) {
return '<span class="fa fa-edit" data-
toggle = "modal"
data - target = "#modal-Edit" > < /span>';
}
}
],
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel',
{
extend: 'pdfHtml5',
orientation: 'Portriat',
pageSize: 'A4'
}
]
});
table = $("#tblAppointment").DataTable();
}
});
});
});
</script>
You can use this:
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList);
var returnData = new object[2];
returnData[0] = data;
returnData[1] = new { f = "error" };
return Json(returnData);
You can integrate the data object in your anonymous object which you are already returning:
return Json(new {data = data, f = "error"});
If you do it like this, you can access the data object in your ajax call like this:
success: function (_data) {
var returnedData = _data.data;
}
Which means you have to adjust your map method call where you are preparing the data array for the table. Instead of:
var arr = $.map(JSON.parse(_data), function (el) { return el });
call it with the data object _data.data:
var arr = $.map(JSON.parse(_data.data), function (el) { return el });
This should do the trick.
I would potentially approach in the following manner, extend the JsonResult to include a status code. This way you can dictate the level of success to the Ajax request.
public class JsonResultWithStatusCode : JsonResult
{
private readonly HttpStatusCode statusCode;
public JsonResultWithStatusCode(object data, HttpStatusCode statusCode)
{
Data = data;
this.statusCode = statusCode;
}
public override void ExecuteResult(ControllerContext context)
{
context.RequestContext.HttpContext.Response.StatusCode = (int)statusCode;
base.ExecuteResult(context);
}
}
Then inside your controller:
if(...)
{
var model = JsonConvert.SerializeObject(...);
return new JsonResultWithStatusCode(model, HttpStatusCode.Ok)
}
else
{
var model = new { error = "..." };
return new JsonResultWithStatusCode(model, HttpStatusCode.InternalServerError);
}
Then inside your Ajax you would be able to read the status code and then read the body.
.success: function(response) {
console.log(response.status); // Status Code (200 or 500 based on above)
console.log(response.data); // Our model based on above, one writing error the other actual model data.
}
All you would have to do would be read based on the server output.
I am trying to make a spline chart using highcharts that updates every second.
The data comes from the DB.
my script is :
<script>
$(function () {
var c = [];
var d = [];
$('#container').highcharts({
chart: {
type: 'spline',
events: {
load: getData
}
},
title: {
text: 'PUNCHING DETAILS'
},
xAxis: {
categories: c
},
yAxis: {
title: {
text: 'punching'
},
labels: {
formatter: function () {
return this.value ;
}
}
},
tooltip: {
crosshairs: true,
shared: true
},
series: [{
name: 'PUNCHING',
data: d
}]
});
});
function getData() {
alert("hi");
$.ajax({
url: "Default.aspx/GetData",
dataType: 'json',
success: function (data) {
console.log(data)
var categories = [];
var seriesData = [];
$.each(data, function (i, e) {
categories.push(i);
seriesData.push(parseInt(e));
});
chart.xAxis[0].setCategories(categories);
chart.series[0].setData(seriesData);
setTimeout(requestData, 1000);
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert(errorThrown);
},
cache: false
});
}
</script>
And cs code is :
public partial class ajax_main_Testpages_Realtime_Graph_Default : System.Web.UI.Page
{
[System.Web.Services.WebMethod()]
public static string GetData()
{
String con1 = ConfigurationManager.ConnectionStrings["myConnectionString"].ToString();
List<string> list_time = new List<string>();
List<int> list_count = new List<int>();
var serie_line_Dept = new { data = new List<object>() };
string query = #"select item_count,entered_time p_time from st_request where rownum<=10";
OdbcConnection connection = new OdbcConnection(con1);
connection.Open();
OdbcCommand cmdSelect = connection.CreateCommand();
cmdSelect.CommandText = query;
OdbcDataReader readerSelect = cmdSelect.ExecuteReader();
while (readerSelect.Read())
{
serie_line_Dept.data.Add(new List<object>() { readerSelect["p_time"].ToString(), int.Parse(readerSelect["item_count"].ToString()) });
list_time.Add(readerSelect["p_time"].ToString());
list_count.Add(int.Parse(readerSelect["item_count"].ToString()));
}
JavaScriptSerializer oSerializer1 = new JavaScriptSerializer();
return oSerializer1.Serialize(serie_line_Dept);
}
}
I get the this error: Unexpected token <.
No graph is displayed.
I referred here for the above code.
I am new to json and jquery, I am unable to solve this.
Can anyone please help me on this?
Thanks in advance.
I am using a web service that gets data from my active directory and returns an array of objects to my javascript. The problem is the I am the response encapsulated in Object with _type included when I just want to return the value of the object like this
([{ value: "one", label: "Foo" }, { value: "two", label: "Bar" }]).
But I am receiving this
[Object { __type="Service+NameDTO", value: "one", label: "Foo"}, Object { __type="Service+NameDTO", value: "two", label: "Bar"}]
Here is my c#
public NameDTO[] GetCompletionList(string prefix)
{
var nameList = new List<NameDTO>();
DirectorySearcher search = new DirectorySearcher();
string strPath = search.SearchRoot.Path;
DirectoryEntry entry = new DirectoryEntry(strPath);
search.PageSize = 1000;
search.Filter = "(&(objectClass=user)(objectCategory=person)(displayName=*" + prefix + "*))";
foreach (SearchResult sResultSet in search.FindAll())
{
if (sResultSet.Properties["mail"].Count > 0)
{
var dto = new NameDTO()
{
label = (string)sResultSet.Properties["displayName"][0],
value = (string)sResultSet.Properties["mail"][0],
};
nameList.Add(dto);
}
}
NameDTO[] myArray = nameList.ToArray();
return myArray;
}
public class NameDTO
{
public string label { get; set; }
public string value { get; set; }
}
and my javascript
<script type="text/javascript">
$(document).ready(function () {
$('#tokenfield').tokenfield({
autocomplete: {
source: function (request, response) {
$.ajax({
url: '<%#ResolveUrl("~/Service1.asmx/GetCompletionList") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return data
}))
},
success: function(response) {
$.each(response, function(key, val) {
alert(val.id);
});
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
search: function () {
var term = this.value;
if (term.length < 3) {
return false;
}
},
focus: function () {
// prevent value inserted on focus
return false;
},
},
});
});
</script>
You probably need some typical JSON builder.
Server-side, you can make dictionaries, arrays, etc and throw everything into a
JsonMapper.ToJson(jsonDict)
call.
This function in my project indirectly calls JsonSerializer(), the Newtonsoft JSON handler. Very useful for both serializing and deserializing the JSON.
I may be misinterpreting your question, though; a bit vague.
http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx is pretty darn relevant here, and very useful.
It came up that you might need this:
var jsonString = #Model; //or however you get your string.
var json = JSON.parse(jsonString);
I am using jQuery AutoComplete to fetch results from a DataBase based on the value inputted. The user will then click a search button to tell the page to search for that specific entries details.
I want to get 2 values, the Name and Title. I only want to display the Name to the user, while the page uses the Title as a search criteria.
eg: When a person types in Vehicle, the result will display Vehicle1, Vehicle2 in a list.
When the user clicks on Vehicle1, a hidden box will be issues with the Title, which would be Bike, and such as with Vehicle2, which will issue the hidden box with Car.
I can get the Name to show in the text box properly, but I cannot for the life of me (And after 2 days of searching) bind the Title to a hidden box.
JavaScript:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".tb").autocomplete({
source: function (request, response) {
$.ajax({
url: "AutoComplete.asmx/FetchEmailList",
data: "{ 'prefix': '" + request.term + "' }",
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.Title,
label: item.Name
};
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
ASPX Code:
<div class="ui-widget" >
<asp:TextBox ID="tbAuto" class="tb" runat="server">
</asp:TextBox>
<asp:TextBox runat="server" ID="tbHidden" class="tb"></asp:TextBox>
</div>
CodeBehind:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class AutoComplete : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Employee> FetchEmailList(string prefix)
{
var emp = new Employee();
var fetchEmail = emp.GetEmployeeList(prefix)
.Where(m => m.Name.ToLower().StartsWith(prefix.ToLower()));
return fetchEmail.ToList();
}
}
CompletionClass: (Excuse the naming)
public class Employee
{
public string Title { get; set; }
public string Name { get; set; }
public string value { get; set; }
public List<Employee> GetEmployeeList(string prefixText)
{
List<Employee> cmpList = new List<Employee>();
SqlConnection db = DataConn.SqlConnection();
db.Open();
SqlTransaction transaction = db.BeginTransaction();
//var array = new ArrayList();
try
{
SqlCommand command = new SqlCommand("Select [something] FROM vwGetDetails WHERE [something_else] LIKE N'%" + prefixText + "%' ORDER BY [thatOther_thing] ASC", db, transaction);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
cmpList.Add(new Employee() { Name = reader["Value1"].ToString(), Title = "Value1_Cat", value = "Value1_Cat"});
}
}
command = new SqlCommand("Select [something] FROM [somewhere] WHERE [thingy] LIKE N'%" + prefixText + "%' ORDER BY [previousThingy] ASC", db, transaction);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
cmpList.Add(new Employee() { Name = reader["Value2"].ToString(), Title = "Value2_Cat", value = "Value2_Cat"});
}
}
transaction.Commit();
}
catch (SqlException)
{
transaction.Rollback();
cmpList.Add(new Employee() { Name = "Problem Getting Results.", value = "Error"});
//array.Add("Problem Getting Results.");
}
if (cmpList.Count == 0)
cmpList.Add(new Employee() { Name = "Nothing to Display.", value = "Info"});
//array.Add("Nothing to Display.");
//return array;
return cmpList;
}
}
Those modifications to your JavaScript should do the trick:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('input[name$="tbAuto"]').autocomplete({
source: function (request, response) {
$.ajax({
url: "AutoComplete.asmx/FetchEmailList",
data: "{ 'prefix': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response(data.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
focus: function(event, ui) {
$('input[name$="tbAuto"]').val(ui.item.Name);
return false;
},
select: function(event, ui) {
$('input[name$="tbAuto"]').val(ui.item.Name);
$('input[name$="tbHidden"]').val(ui.item.Title);
return false;
}
}).data('autocomplete')._renderItem = function(ul, item) {
return $('<li>').data('item.autocomplete', item).append('<a>' + item.Name + '</a>').appendTo(ul);
};
});
</script>
The assumption here is that the selectors returns exactly the element which we are working on, if not they need to be adjusted.
Cool. I've been googling for this solution for days... excellent clean code!
Just a small remark: using jqueryUI 1.10, this
throws javascript exception.
.data('autocomplete')._renderItem = function(ul, item) {...
I've used
.data('ui-autocomplete')._renderItem = function(ul, item) {...
and everything works great.