Ajax call work slow.Can make it fast? - javascript

I'm filling "ReportToadd" dropdownlist form "ddlLanguage" dropdownlist when select index change through JavaScript and ajax in asp.net mvc.This work fine but take much time to fill child dropdownlis"ReportToadd".it take 4 to 5 second to fill second dropdownlist.How can make it fast.please help and thanks in advance
JavaScript code:
$(function () {
$('select#ddlLanguage').change(function () {
var languageId = $(this).val();
var projectType ='#(TempData["projectType"])';
$.ajax({
url: "/SEI/Report/FillReport",
type: 'POST',
data: JSON.stringify({ languageId: languageId, projectType: projectType }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$("#ReportToAdd").html("");
$.each(data, function (key, result) {
$('select#ReportToAdd').append(
'<option value="' + result.Value + '">'
+ result.Text +
'</option>');
});
}
});
});
});
and dropdownlist are:
string projectType = "SEI_ADULT";
#Html.DropDownList("ddlLanguage", SixSeconds.Utils.SelectList<SixSeconds.Models.Language>("Name", ""), new { #id = "ddlLanguage", style = "width:300px;" }) <br />
TempData["projectType"] = projectType;
#Html.DropDownList("ReportToAdd", Enumerable.Empty<SelectListItem>(), new { #id = "ReportToAdd", style = "width:300px;" })
and Json method is like
public JsonResult FillReport(int languageId,string projectType,string selectedValue, bool showCredits = true)
{
DataAccessObject<ReportType> dao = new DataAccessObject<ReportType>();
DataAccessObject<Language> ldao = new DataAccessObject<Language>();
//IEnumerable<ReportType> list = criteria != null ? dao.Filter(criteria) : dao.All().ToList();
IEnumerable<ReportType> list = dao.All().ToList();
IEnumerable<Language> Llist = ldao.All().ToList();
list = list.Where(a => a.ProjectType.ToString() == projectType).ToList();
list = list.OrderBy(r => r.CustomOrder);
List<SelectListItem> result = new List<SelectListItem>();
result.Add(new SelectListItem() { Value = "", Text = "" });
foreach (ReportType t in list)
{
foreach (Language l in t.Languages.Where(a=>a.Id==languageId).ToList())
{
string displayText = t.Name + " (" + l.Name + ")" + (showCredits ? " - " + (t.Code == "BTP" ? 10 : t.Credits) + " " + App_GlobalResources.FieldLabels.Credits : "");
string value = t.Id + "-" + l.Id + "-" + (t.Code == "BTP" ? 10 : t.Credits) + "-" + t.Code + "-" + l.Code.Replace("-", "_");
result.Add(new SelectListItem() { Selected = (selectedValue == value), Value = value, Text = displayText });
}
}
return Json(result);
}

One way of updating your db query is to not use All and pass down the Where.
Also, Llist is never used so you are getting all the Languages from the db for nothing.
try:-
//IEnumerable<Language> Llist = ldao.All().ToList();
IEnumerable<ReportType> list = dao.Where(a => a.ProjectType.ToString() == projectType)
.OrderBy(r => r.CustomOrder).ToList();
instead of :-
IEnumerable<ReportType> list = dao.All().ToList();
IEnumerable<Language> Llist = ldao.All().ToList();
list = list.Where(a => a.ProjectType.ToString() == projectType).ToList();
list = list.OrderBy(r => r.CustomOrder);
This will pass the where and order by to the db instead of doing it in code.

Related

Update a value on a entry on the table - issue

I have these columns on my table:
CardNumber
DateRegister
TimeRegister
DateExit
TimeExit
I read a value that is in a box, and when I press enter, the
Cardnumber, DateRegister,TimeRegister is add to the SQL Database
So I'll have like
CardNumber|DateRegister|TimeRegister|DateExit|TimeExit
124455|23-10-2022|11:00|null|null|
My Issue is, If I read the same card again, before I need to see if there is already one entrance on database with that card number, that don't have still DateExit and TimeExit.
If dont, I need to update that line, with that information, of if is a new one, will add a new entrance on the database
This is my code:
#section readcard{
<script>
$(function () {
$("#readONchange").change(function () {
var param1 = new Date();
var param2 = param1.getDate() + '/' + (param1.getMonth() + 1) + '/' + param1.getFullYear();
var param3 = param1.getHours() + ':' + param1.getMinutes() + ':' + param1.getSeconds();
var es = {};
/*es.IdCartao = $("#readONchange").val();*/
/*es.DateRegister = param2;*/
//Le cartao / Le data / Le Hora
es.IdCartao = $("#readONchange").val();
es.DateRegister = param2;
es.TimeRegister = param3;
if (es.IdCartao != null)
{
} else if (es.IdCartao == null) {
empregados.IdCartao = es.IdCartao(id);
(es.IdCartao == $("#readONchange").val && es.DateRegister != null && es.TimeRegister != null)
es.TimeExit = param3;
alert(es.IdCartao == $("#readONchange").val);
} else {
alert("erro")
}
alert("Register ADD!")
$.ajax({
type: "POST",
url: '#Url.Action("AddReport")',
data: '{es: ' + JSON.stringify(es) + '}',
dataType: 'json',
contentType: "application/json; charset=utf-8",
sucess: function () {
alert("Data Insert with Sucess");
},
error: function () {
alert("ERROR! on the regist");
}
});
});
});
</script>

Drop down list (Asp.net web forms) not getting populated with data

I have jQuery call to get the data and a dropdown list on the UI, which is not populating the data.
I have tried many ways, commented is the code I used.
Let me know if I did something wrong in the code.
var questionData;
var optionData;
$(document).ready(function () {
$.ajax({
url: 'coaching-assessment-tool.aspx/GetCATQuestionAndOptions',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
questionData = data.d[0];
optionData = data.d[1];
console.log(questionData[0].QuestionText);
console.log("Question Data", questionData);
console.log("Option Data", optionData);
//Questions
document.getElementById('firstQuestion').innerHTML = questionData[0].QuestionText;
document.getElementById('secondQuestion').innerHTML = questionData[1].QuestionText;
document.getElementById('thirdQuestion').innerHTML = questionData[2].QuestionText;
document.getElementById('fourthQuestion').innerHTML = questionData[3].QuestionText;
document.getElementById('fifthQuestion').innerHTML = questionData[4].QuestionText;
document.getElementById('sixthQuestion').innerHTML = questionData[5].QuestionText;
document.getElementById('seventhQuestion').innerHTML = questionData[6].QuestionText;
document.getElementById('eighthQuestion').innerHTML = questionData[7].QuestionText;
document.getElementById('ninthQuestion').innerHTML = questionData[8].QuestionText;
document.getElementById('tenthQuestion').innerHTML = questionData[9].QuestionText;
//Responses
//var ddlFirstResponse = document.getElementById('#ddlFirstResponse');
//ddlFirstResponse.empty();
$(function () {
$('#ddlFirstResponse').append($("<option></option>").val('').html(''));
$.each(optionData, function (key, value) {
//console.log('option: ' + value.OptionText + ' | id: ' + value.OptionId);
//$('#ddlFirstResponse').append($("<option></option>").val(value.OptionId).html(value.OptionText));
$("#ddlFirstResponse").append("<option value='" + value.OptionId + "'>" + value.OptionText + "</option>");
});
});
},
error: function (error) {
console.log(error);
alert('Error retrieving data. Please contact support.');
}
});
});
<asp:DropDownList ID="ddlFirstResponse" runat="server"></asp:DropDownList>
Your data return handler is a bit off when the returned data is acquired, you can do the following to alleviate that:
function (data, status) {
var json = data;
obj = JSON.parse(json);
var opt = null;
$("#targetIDOfControl").empty();
for (i = 0; i < obj.People.length; i++) {
if (i < obj.People.length) {
opt = null;
opt = document.createElement("option");
document.getElementById("targetIDOfControl").options.add(opt);
opt.text = obj.People[i].Name;
opt.value = obj.People[i].ID;
}
}
The above example creates an option then sets its text and values. Then replicates more options depending on the amount of indexes in the JSON array returned.
Since I received response a bit late, I did trial and error, and finally made it to work.
Here is the code changes I made to make it work.
var ddlFirstResponse = **$("[id*=ddlFirstResponse]");**
ddlFirstResponse.empty();
$(function () {
ddlFirstResponse.append($("<option></option>").val('').html('-- Select value --'));
$.each(industryOptionData, function (key, value) {
//console.log('option: ' + value.OptionText + ' | id: ' + value.OptionId);
ddlFirstResponse.append($("<option></option>").val(value.OptionId).html(value.OptionText));
//ddlFirstResponse.append("<option value='" + value.OptionId + "'>" + value.OptionText + "</option>");
});
});
//var ddlFirstResponse = document.getElementById('ddlFirstResponse'); --> Failed
var ddlFirstResponse = $("[id*=ddlFirstResponse]"); --> worked

JQuery : How to add list of objects in Ajax

It's one of my first time I using JQuery/AJAX and I would like to get your help in order to give a list of objects in my dropdown field.
I have this function :
function get_sub_method_options(keep_cur) {
var sel_option = $('select#id_method-group').find("option:selected");
var sel_val = sel_option.val();
console.log(sel_val);
if (sel_val === '') {
console.log('none sorting group');
$("select#id_method-sub_method").empty();
$("select#id_method-sub_method").append('<option value=""> test </option>'); //here add list of all submethods
return;
}
data = {
'test_method': $('select#id_method-test_method').find("option:selected").val(),
'group': sel_val
};
$.ajax({
method: "GET",
url: '{% url 'ajax_method_submethod' %}',
data: data
}).done(function (result) {
reset_select('id_method-sub_method');
for (var i = 0; i < result['results'].length; i++) {
if (keep_cur > 0 & keep_cur == result['results'][i].id)
$("select#id_method-sub_method").append('<option value="' + result['results'][i].id + '" selected>' + result['results'][i].text + '</option>');
else
$("select#id_method-sub_method").append('<option value="' + result['results'][i].id + '">' + result['results'][i].text + '</option>');
}
;
});
}
And I have a Python/Django function :
def ajax_method_submethod(request):
test_method_id = request.GET.get("test_method", "")
group_id = request.GET.get("group", "")
sub_methods_all = SubMethod.objects.all()
sub_methods = Method.objects.filter(test_method_id=test_method_id).filter(
group_id=group_id
)
results2 = []
for item in sub_methods_all:
results2.append({'id': item.id, 'text': item.name})
print(results2)
results = []
for item in sub_methods:
results.append({'id': item.sub_method.id, 'text': item.sub_method.name})
return HttpResponse(json.dumps({'err': 'nil', 'results': results, 'results2': results2}), content_type='application/json')
I would like to import into my dropdown field values from results2 (python file) when I have sel_val is empty :
if (sel_val === '') {
...
}
So how I could rewrite this part :
if (sel_val === '') {
console.log('none sorting group');
$("select#id_method-sub_method").empty();
$("select#id_method-sub_method").append('<option value=""> test </option>'); //here add list of all submethods
return;
}
Like this :
if (sel_val === '') {
$("select#id_method-sub_method").empty();
for (var i = 0; i < result['results2'].length; i++) {
$("select#id_method-sub_method").append('<option value="' + result['results2'][i].id + '">' + result['results2'][i].text + '</option>'); //here add list of all submethods
}
return;
}
with for loop and append all elements from results2 to my dropdown field ? The issue is actually with result['results2']
Hopfully it's readable and understandable.
Thank you !
EDIT :
As #Darren Crabb said, it's a possible out of scope.
So I rewrote my JS like this :
if (!sel_val) {
reset_select('id_method-sub_method');
$("select#id_method-sub_method").empty();
var all = "{{ results2 }}";
for (var i = 0; i < all.length; i++) {
$("select#id_method-sub_method").append('<option value="' + all[i].id + '">' + all[i].text + '</option>'); //here add list of all submethods
}
return;
}
And I defined in my python file : context['results2'] = SubMethod.objects.all()
I get this :

wpf webbrowser javascript callback

if have javascript:
function calculateValues(callback)
{
window.external.getHistoryRange(0,1,"",function(res){
var hist = eval(res);
histCount = hist.historyCount;
hist = hist.historyContent;
if (histCount == 0)
{
return;
}
$("#history_table").show();
var $row = addAlertHistoryRow(hist[0]);
var rowHeight = $row.height();
pageItemsCount = Math.floor(contentHeight / rowHeight);
curPageNum = 0;
$row.remove();
if (callback) callback();
});
}
in function calculateValues(callback) callback parameter is:
function(){statItempos = 0; gethistoryandshow(pageNum,startItemsPos,callback);}
and c# code, that works with that script (ObjectForScripting):
public string getHistoryRange(string strVar0 = "", string strVar1 = "", string strVar2 = "", string strVar3 = "")
{
string res = "";
using (DeskAlertsDbContext db = new DeskAlertsDbContext())
{
var alerts = db.HistoryAlerts.OrderBy(a => a.ReciveTime)
.Include(b => b.alert.WINDOW)
.ToList();
foreach (var alert in alerts)
{
res += ("{\"id\":" + System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Alert_id) +
",\"date\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(
alert.ReciveTime.ToString(CultureInfo.InvariantCulture)) + "\",\"alert\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alerttext) + "\",\"title\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Title) + "\",\"acknow\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Acknown) + "\",\"create\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Create_date) + "\",\"class\":\"" +
"1" + "\",\"urgent\":\"" + System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Urgent) +
"\",\"unread\":\"" + Convert.ToInt32(alert.isclosed).ToString() + "\",\"position\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Position) + "\",\"ticker\":\"" +
alert.alert.Ticker + "\",\"to_date\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.To_date) + "\"},");
}
res = res.TrimEnd(','); //trim right ","
res = "({\"historyCount\":" + alerts.Count.ToString() + ",\"historyContent\":[" + res + "]});";
Browserwindow.Wb.InvokeScript("eval", new object[] { strVar3 });
Browserwindow.Wb.InvokeScript("CallbackFunction", new object[] { res });
return res;
}
}
On string: "Browserwindow.Wb.InvokeScript("eval", new object[] { strVar3 });"
I try to call anonymous function from javascript and have an error.
Question is: how to make this logic. How to perform the JS function of the parameters a different function. And then continue JS. If i tryed to give name to function, and invoke it, function works, but global context(if (callback) callback();) becomes unavailible
Your callback function name is not correct.
Replace
Browserwindow.Wb.InvokeScript("CallbackFunction", new object[] { res });
With
Browserwindow.Wb.InvokeScript("calculateValues", new object[] { res });
Hmmm... Just maked my variable dynamic (not string), and all worked
public string getHistoryRange(string strVar0 = "", string strVar1 = "", string strVar2 = "", dynamic strVar3 = null)
{
string res = "";
using (DeskAlertsDbContext db = new DeskAlertsDbContext())
{
var alerts = db.HistoryAlerts.OrderBy(a => a.ReciveTime)
.Include(b => b.alert.WINDOW)
.ToList();
foreach (var alert in alerts)
{
res += ("{\"id\":" + System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Alert_id) +
",\"date\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(
alert.ReciveTime.ToString(CultureInfo.InvariantCulture)) + "\",\"alert\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alerttext) + "\",\"title\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Title) + "\",\"acknow\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Acknown) + "\",\"create\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Create_date) + "\",\"class\":\"" +
"1" + "\",\"urgent\":\"" + System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Urgent) +
"\",\"unread\":\"" + Convert.ToInt32(alert.isclosed).ToString() + "\",\"position\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Position) + "\",\"ticker\":\"" +
alert.alert.Ticker + "\",\"to_date\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.To_date) + "\"},");
}
res = res.TrimEnd(','); //trim right ","
res = "({\"historyCount\":" + alerts.Count.ToString() + ",\"historyContent\":[" + res + "]});";
dynamic variable = Browserwindow.Wb.InvokeScript("eval", new object[] { strVar3 });
variable(res);
return res;
}
}

data in alert box through linq

i try to show result in alert box
i try this
[WebMethod]
public static string Jqufunc(int yearP)
{
string res = "[";
ProjectdbEntities a = new ProjectdbEntities();
var b = a.Catg_type;
foreach (var c in b)
{
res += "'" + c.Catg_type1 + "',";
}
res = res.Substring(0, res.Length - 1);
res += "]";
var allprogs = a.Program_type;
string res2 = "[";
foreach (var pr in allprogs)
{
res2 += "{name: '" + pr.Prog_name + "',";
//var y = a.Year_info;
var allcats = a.Catg_type;
res2 += "data:[";
var query = (a.Std_info.Join(a.Catg_type, stdtable => stdtable.Catg_id,
catg => catg.Catg_id, (stdtable, catg) => new {stdtable, catg})
.Join(a.Program_type, t => t.stdtable.Prog_id, prog => prog.Prog_id, (t, prog) => new {t, prog})
.Join(a.Year_info, t => t.t.stdtable.year_id, yea => yea.year_id, (t, yea) => new {t, yea})
.Where(t=>t.t.t.stdtable.year_id==yearP)
.GroupBy(
t =>
new { t.t.t.catg.Catg_type1, t.t.prog.Prog_name, t.yea.year, t.t.t.stdtable.Catg_id },
t => t.t.t.stdtable)
.Select(g => new
{
g.Key.Catg_type1,
g.Key.Prog_name,
g.Key.year,
g.Key.Catg_id,
total_students = g.Select(p=>p.Catg_id).Distinct().Count()
})).ToList();
res2 = res2.Substring(0, res2.Length - 1);
}
res2 += "]";
res2 += "},";
return res + "*" + res2;
}
i try to show in alert box
var webmethod = 'WebForm1.aspx/Jqufunc';
$.ajax({
type: 'POST',
url: webmethod,
data: JSON.stringify({ yearP: $('#DropDownList1').val() }),
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (response) {
alert(JSON.stringify(response.d));;
i have a dropdown in page i filled this dropdown from db
when i select year suppose i select 2014 year from drop down then according to the year 2014 following data is save in db
Catg_type Prog_name year total_students
ComputerScience Bachelors 2014 1
Management Bachelors 2014 1
Finance Masters 2014 3
Management Masters 2014 2
now i want this in alert box
['Management','ComputerScience','Finance']
[{name:'Bachelors','2014',data:1,1,0
name :'Masters,'2014, data:2,0,3}]
but currently data is displayed in alert box like this
['Management','ComputerScience','Finance']
[{name:Bachelors,data:}{name:Masters,data:}]
alert("Name: " + response.d.Prog_name + ", Type: "+ response.d.Catg_type);

Categories

Resources