Why does the usernameOK=1; statement in the ajax function not stay set when I use the alert statement after the $.post function? I need a way to use a variable as a condition for an if statement.
function validateRegistration() {
var username = document.getElementById("userName").value;
var fname = document.getElementById("fName").value;
var lname = document.getElementById("lName").value;
var email = document.getElementById("email").value;
var confirmEmail = document.getElementById("confirmEmail").value;
var password = document.getElementById("userpass").value;
var confirmPass = document.getElementById("confirmPassword").value;
var usernameOK = 0;
$.post("action.php", { field: 'doesUsernameExist', username: username },
function(result){ //if the result is 1
if(result == 1){ //show that the username is available
usernameSuc.innerHTML= username + " is Available.";
var usernameOK=1;
}else if(result == 0){ //show that the username is NOT available
usernameErr.innerHTML="User name: "+username+" is not
available.";
} else {
usernameErr.innerHTML="Something is Wrong";
}
});
alert("usernameOK: "+usernameOK); //This doesn't work. only prints a zero, never 1
if (usernameOK == 1) {
if ((username.length > 5) && (!(/[^a-zA-Z0-9_-]/.test(username)))){
if((fname != "") && (lname != "")){
if((email != "") && (email == confirmEmail)){
if (((email.indexOf(".") > 0) && (email.indexOf("#") > 0))
&& !/[^a-zA-Z0-9.#_-]/.test(email)){
if ((password.length > 7) && (/[a-z]/.test(password))
&& (/[A-Z]/.test(password)) && (/[0-9]/.test(password))){
if (password == confirmPass) {
document.getElementById("submit").className = "btn btn-success";
document.getElementById("submit").removeAttribute("disabled");
}
}
}
}
}
}
} else {
document.getElementById("submit").className = "btn btn-success disabled";
}
}
Figured out a solution. Thought I would post it in case it would help someone else. Changed the order and moved the ajax inside all the conditional if statements so it is the last thing to check instead of the first.
function validateRegistration() {
var username = document.getElementById("userName").value;
var fname = document.getElementById("fName").value;
var lname = document.getElementById("lName").value;
var email = document.getElementById("email").value;
var confirmEmail = document.getElementById("confirmEmail").value;
var password = document.getElementById("userpass").value;
var confirmPass = document.getElementById("confirmPassword").value;
if ((username.length > 5) && (!(/[^a-zA-Z0-9_-]/.test(username)))){
if((fname != "") && (lname != "")){
if((email != "") && (email == confirmEmail)){
if (((email.indexOf(".") > 0)
&& (email.indexOf("#") > 0))
&& !/[^a-zA-Z0-9.#_-]/.test(email)){
if ((password.length > 7)
&& (/[a-z]/.test(password))
&& (/[A-Z]/.test(password))
&& (/[0-9]/.test(password))){
if (password == confirmPass) {
$.ajax({
type: "POST",
url: "action.php",
data: {field: 'doesUsernameExist', username: username },
async: false,
success: function (result) {
if(result == 1) {
document.getElementById("submit").className = "btn btn-success";
document.getElementById("submit").removeAttribute("disabled");
} else {
document.getElementById("submit").className = "btn btn-success disabled";
document.getElementById("submit").setAttribute('disabled', true);
}
},
error: function (result) {
pass = "error"
alert("There was an error with the database");
}
});
}
}
}
}
}
} else {
document.getElementById("submit").className = "btn btn-success disabled";
document.getElementById("submit").setAttribute('disabled', true);
}
}
Related
In our application, I added a validation of each row that you can't have 2 same columns values. I'm done with it but Im having a problem in delete row
Example
There is a delete button in the right side when I clicked it, it gives me an error Cannot read property ..... even tho it is already declared in my data
Error Message
Vue code
deleteRow(i, e){
var month = this.added_items[i].selected_month.id
var chart_of_account_id = this.added_items[i].selected_chart_of_account.id
var count = 0
// var duplicate = false
this.submitStatus = ''
this.duplicate_month = false
this.added_items.filter(function( obj ) {
console.log(this.submitStatus)
if((obj.selected_month.id == month && obj.selected_chart_of_account.id == chart_of_account_id) && obj.id != i){
count++
if(count >= 2)
{
// this.added_items[i].duplicate_month = true
// this.submitStatus = 'ERROR'
// this.duplicate_month = true
}
}
return obj.id !== i;
});
console.log(this.added_items)
e.preventDefault()
},
Question: How can I call my data inside of my filter function? because when I tried any of these: this.submitStatus/this.added_items[i].duplicate_month/this.duplicate_month it gives me an error
You can approach it in two ways
Option 1: Arrow Functions
this.added_items.filter(( obj ) => {
console.log(this.submitStatus)
if(
(
obj.selected_month.id == month &&
obj.selected_chart_of_account.id == chart_of_account_id
) &&
obj.id != i
){
count++
if(count >= 2)
{
// this.added_items[i].duplicate_month = true
// this.submitStatus = 'ERROR'
// this.duplicate_month = true
}
}
return obj.id !== i;
});
Option 2: Bind this
this.added_items.filter(function( obj ) {
console.log(this.submitStatus)
if(
(
obj.selected_month.id == month &&
obj.selected_chart_of_account.id == chart_of_account_id
) &&
obj.id != i
){
count++
if(count >= 2)
{
// this.added_items[i].duplicate_month = true
// this.submitStatus = 'ERROR'
// this.duplicate_month = true
}
}
return obj.id !== i;
}).bind(this);
After upgrading to latest Alloy1.8 update, I have started getting Script Errors for my Listview Transform functions.
[ERROR] : Script Error {
[ERROR] : column = 17;
[ERROR] : line = 4;
[ERROR] : message = "Can't find variable: PartyName";
[ERROR] : stack = "anonymous\ntemplate#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/underscore.js:1267:28\n__alloyId721#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/controllers/appointments/inspectionProposal.js:23:37\ntrigger#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/backbone.js:163:23\nreset#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/backbone.js:746:35\nsuccess#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/backbone.js:759:44\nSync#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/sync/sql.js:180:51\nsync#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy.js:108:28\nfetch#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/backbone.js:763:42\nloadInspectionDetails#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/controllers/appointments/inspectionProposal.js:58:43\nController#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/controllers/appointments/inspectionProposal.js:377:26\ncreateController#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy.js:232:54\nController#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/controllers/appointments/appointmentContainer.js:716:56\ncreateController#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy.js:232:54\nopenNewPage#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/common/common.js:759:41\nfile:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/controllers/dashboard/dashboardAppointments.js:615:35";
[ERROR] : }
Here is my transform function which does return transform.PartyName
function addLastInspectedDate(model) {
var transform = model.toJSON();
var appointmentDetailsCollection = Alloy.createCollection(modelConfiguration.appointmentList);
appointmentDetailsCollection.fetch({
query: {
statement: query.getAppointmentListById,
params: [ transform.AppointmentId ]
}
});
appointmentDetailsCollection.each(function(eachRecord) {
var firstName = eachRecord.get("FirstName");
var lastName = eachRecord.get("LastName");
var partyName = "";
partyName += null != firstName ? firstName : "";
partyName += "" == partyName ? null != lastName ? lastName : "" : " " + lastName;
Ti.API.info("partyName:" + partyName);
transform.PartyName = partyName;
transform.StreetName = eachRecord.get("StreetName");
var city = eachRecord.get("City");
var stateCode = eachRecord.get("StateCode");
var postalCode = eachRecord.get("PostalCode");
var addressLine2 = "";
addressLine2 += null != city ? city : "";
addressLine2 += "" == addressLine2 ? (null != stateCode ? stateCode : "") + " " + (null != postalCode ? postalCode : "") : "," + (null != stateCode ? stateCode : "") + " " + (null != postalCode ? postalCode : "");
Ti.API.info("addressLine2:" + addressLine2);
transform.AddressLine2 = addressLine2;
transform.DateLastInspected = transform.DateInspected;
transform.AppointmentId = transform.AppointmentId;
});
return transform;
}
ListView Bindings:
<ItemTemplate name="selectedInspectionProposal" height="Ti.UI.SIZE" backgroundColor="#119050">
<View height="Ti.UI.SIZE" width="Ti.UI.FILL" top="0" bottom="1" backgroundColor="#fff">
<View class="selectedInspectionData vgroup" id="inspectionDataContainerId" top="10">
<Label class="selectedGenInfo" bindId="partyName" id="partyNameId"></Label>
<Label class="selectedGenInfo" bindId="addressLineOne" id="addressLine1Id"></Label>
<Label class="selectedGenInfo" bindId="addressLineTwo" id="addressLine2Id" bottom="15"></Label>
<Label class="selectedGenInfo" bindId="inspectedDate" id="inspectedDateId" bottom="10"></Label>
</View>
</View>
</ItemTemplate>
</Templates>
<ListSection id="section" dataCollection="Inspection" dataTransform="addLastInspectedDate">
<ListItem template="inspectionProposal" partyName:text="{PartyName}" addressLineOne:text="{StreetName}" addressLineTwo:text="{AddressLine2}" inspectedDate:text="{DateLastInspected}" appointmentId:text="{AppointmentId}" selectedBackgroundColor="#119050"></ListItem>
</ListSection>
inspectionProposal.js generated with Alloy 1.8.2
function __alloyId726(e) {
if (e && e.fromAdapter) return;
var opts = __alloyId726.opts || {};
var models = __alloyId725.models;
var len = models.length;
var __alloyId721 = [];
for (var i = 0; len > i; i++) {
var __alloyId722 = models[i];
__alloyId722.__transform = addLastInspectedDate(__alloyId722);
var __alloyId724 = {
template: "inspectionProposal",
partyName: {
text: _.template("{PartyName}", __alloyId722.__transform, {
interpolate: /\{([\s\S]+?)\}/g
})
},
addressLineOne: {
text: _.template("{StreetName}", __alloyId722.__transform, {
interpolate: /\{([\s\S]+?)\}/g
})
},
addressLineTwo: {
text: _.template("{AddressLine2}", __alloyId722.__transform, {
interpolate: /\{([\s\S]+?)\}/g
})
},
inspectedDate: {
text: _.template("{DateLastInspected}", __alloyId722.__transform, {
interpolate: /\{([\s\S]+?)\}/g
})
},
appointmentId: {
text: _.template("{AppointmentId}", __alloyId722.__transform, {
interpolate: /\{([\s\S]+?)\}/g
})
},
properties: {
selectedBackgroundColor: "#119050"
}
};
__alloyId721.push(__alloyId724);
}
opts.animation ? $.__views.section.setItems(__alloyId721, opts.animation) : $.__views.section.setItems(__alloyId721);
}
inspectionProposal.js generated with Alloy 1.7.6
function __alloyId742(e) {
if (e && e.fromAdapter) return;
var opts = __alloyId742.opts || {};
var models = __alloyId741.models;
var len = models.length;
var __alloyId737 = [];
for (var i = 0; len > i; i++) {
var __alloyId738 = models[i];
__alloyId738.__transform = addLastInspectedDate(__alloyId738);
var __alloyId740 = {
template: "inspectionProposal",
partyName: {
text: "undefined" != typeof __alloyId738.__transform["PartyName"] ? __alloyId738.__transform["PartyName"] : __alloyId738.get("PartyName")
},
addressLineOne: {
text: "undefined" != typeof __alloyId738.__transform["StreetName"] ? __alloyId738.__transform["StreetName"] : __alloyId738.get("StreetName")
},
addressLineTwo: {
text: "undefined" != typeof __alloyId738.__transform["AddressLine2"] ? __alloyId738.__transform["AddressLine2"] : __alloyId738.get("AddressLine2")
},
inspectedDate: {
text: "undefined" != typeof __alloyId738.__transform["DateLastInspected"] ? __alloyId738.__transform["DateLastInspected"] : __alloyId738.get("DateLastInspected")
},
appointmentId: {
text: "undefined" != typeof __alloyId738.__transform["AppointmentId"] ? __alloyId738.__transform["AppointmentId"] : __alloyId738.get("AppointmentId")
},
properties: {
selectedBackgroundColor: "#119050"
}
};
__alloyId737.push(__alloyId740);
}
opts.animation ? $.__views.section.setItems(__alloyId737, opts.animation) : $.__views.section.setItems(__alloyId737);
}
I got JqGrid with modified cellEdit ( full up-down-left-right cell navigation ).
Here is bits of jqgrid.src:
if (e.keyCode === 37) {
if(!$t.grid.hDiv.loading ) {
{$($t).jqGrid("prevCell",iRow,iCol);} //left
} else {
return false;
}
}
if (e.keyCode === 39) {
if(!$t.grid.hDiv.loading ) {
{$($t).jqGrid("nextCell",iRow,iCol);} //right
} else {
return false;
}
}
if (e.keyCode === 38) {
if(!$t.grid.hDiv.loading ) {
{$($t).jqGrid("prevRow",iRow,iCol);} //up
} else {
return false;
}
}
if (e.keyCode === 40) {
if(!$t.grid.hDiv.loading ) {
{$($t).jqGrid("nextRow",iRow,iCol);} //down
} else {
return false;
}
}
and others
nextCell : function (iRow,iCol) {
return this.each(function (){
var $t = this, nCol=false, i;
if (!$t.grid || $t.p.cellEdit !== true) {return;}
// try to find next editable cell
for (i=iCol+1; i<$t.p.colModel.length; i++) {
if ($t.p.colModel[i].editable ===true && $t.p.colModel[i].hidden !== true ) {
//alert($t.p.colModel[i-1].hidden);
nCol = i; break;
}
}
if(nCol !== false) {
$($t).jqGrid("editCell",iRow,nCol,true);
} else {
if ($t.p.savedRow.length >0) {
$($t).jqGrid("saveCell",iRow,iCol);
}
}
});
},
prevCell : function (iRow,iCol) {
return this.each(function (){
var $t = this, nCol=false, i;
if (!$t.grid || $t.p.cellEdit !== true) {return;}
// try to find next editable cell
for (i=iCol-1; i>=0; i--) {
if ($t.p.colModel[i].editable ===true && $t.p.colModel[i].hidden !== true ) {
nCol = i; break;
}
}
if(nCol !== false) {
$($t).jqGrid("editCell",iRow,nCol,true);
} else {
if ($t.p.savedRow.length >0) {
$($t).jqGrid("saveCell",iRow,iCol);
}
}
});
},
prevRow : function (iRow,iCol) {
return this.each(function (){
var $t = this, nCol=false, i;
if (!$t.grid || $t.p.cellEdit !== true) {return;}
// try to find next editable cell
iRow--;
iCol++;
for (i=iCol-1; i>=0; i--) {
if ( $t.p.colModel[i].editable ===true) {
nCol = i; break;
}
}
if(nCol !== false) {
$($t).jqGrid("editCell",iRow,nCol,true);
} else {
if ($t.p.savedRow.length >0) {
$($t).jqGrid("saveCell",iRow,iCol);
}
}
});
},
nextRow : function (iRow,iCol) {
return this.each(function (){
var $t = this, nCol=false, i;
if (!$t.grid || $t.p.cellEdit !== true) {return;}
// try to find next editable cell
iRow++;
iCol++;
for (i=iCol-1; i>=0; i--) {
if ( $t.p.colModel[i].editable ===true) {
nCol = i; break;
}
}
if(nCol !== false) {
$($t).jqGrid("editCell",iRow,nCol,true);
} else {
if ($t.p.savedRow.length >0) {
$($t).jqGrid("saveCell",iRow,iCol);
}
}
});
}
Also i got autocomplete working with JqGrid event afterEditCell:
getautocompl = function(rowid,cellname,value,iRow,iCol){
setTimeout(function() { $("#"+iRow+"_"+cellname).select().focus();},10);
if(cellname!=='date_factory' || cellname!=='date_otgr_factory' || cellname!=='date_shipment' || cellname!=='date_sklad' || cellname!=='kolinkor'
|| cellname!=='kolkor' || cellname!=='kol_quantity' || cellname!=='description') {
$("#"+iRow+"_"+cellname).autocomplete({
source:"../../phpmon/autocomplete.php?fname="+cellname,
delay:250,
minLength: 2});
}
}
Problem here is that i cant manage autocomplete hotkeys to work, when i hit "down" button it just goes to next cell, rather then to any of the autocomplete options.
you could suppress jqgrid navigation when autocomplete element is visible. something like:
$(document).keydown(function( fn ){
var key = fn.keyCode;
if( $("#autocomplete") && key == 40)
/* your autocomplete action*/
});
Its not quite what i needed, but it helped me to make it.
I just modified jqgrid source code like this :
if (e.keyCode === 40) {
if(!$t.grid.hDiv.loading ) {
if ($('.ui-menu-item').length < 1) {
{$($t).jqGrid("nextRow",iRow,iCol);} //down
}
} else {
return false;
}
}
Where .ui-menu-item is class of autocomplete widget.
thk a lot
I have a project which using DataTables. Its working as ajax request. Its completing in 8-12 seconds. I need to optimize this code but i don't know how. String Process is worst part.
public JsonResult PageModel(Models.DataTable.ParamModel model, byte type)
{
DateTime startTime = DateTime.Now;
using (var db = Helper.Context())
{
var allEntries = db.MembershipVacations.Where(i => i.Type == type).ToList();
IEnumerable<DatabaseProcedure.Models.MembershipVacation> list = new List<DatabaseProcedure.Models.MembershipVacation>();
Func<DbModels.MembershipVacation, string> orderingFunction = (c =>
model.iSortCol_0 == 0 ? c.Membership.Username : "");
Func<DbModels.MembershipVacation, DateTime> dateOrderingFunction = (c =>
model.iSortCol_0 == 1 ? c.PostDate :
model.iSortCol_0 == 3 ? c.StartDate :
model.iSortCol_0 == 4 ? c.EndDate : DateTime.MaxValue);
/*Func<DbModels.MembershipVacation, string> orderingFunction = (c => model.iSortCol_0 == 1 ? c.ID.ToString() :
model.iSortCol_0 == 2 ? c.Membership.Username :
c.Description);*/
if (User.IsInRole("Admin"))
{
if (model.sSearch.IsNull())
{
if (model.sSortDir_0 == "asc")
{
list = allEntries
.OrderBy(orderingFunction);
if (model.iSortCol_0 == 1 || model.iSortCol_0 == 3 || model.iSortCol_0 == 4)
{
list = allEntries.OrderBy(dateOrderingFunction);
}
}
else
{
list = allEntries
.OrderByDescending(orderingFunction);
if (model.iSortCol_0 == 1 || model.iSortCol_0 == 3 || model.iSortCol_0 == 4)
{
list = allEntries.OrderByDescending(dateOrderingFunction);
}
}
list = list
.Skip(model.iDisplayStart)
.Take(model.iDisplayLength);
}
else
{
list = allEntries
.Where(i =>
i.Membership != null ? i.Membership.Username.Contains(model.sSearch, StringComparison.OrdinalIgnoreCase) : false
|| i.Membership != null && i.Membership.Department != null ? i.Membership.Department.Name.Contains(model.sSearch, StringComparison.OrdinalIgnoreCase) : false
|| i.StartDate.ToString().Contains(model.sSearch, StringComparison.OrdinalIgnoreCase)
|| i.EndDate.ToString().Contains(model.sSearch, StringComparison.OrdinalIgnoreCase));
if (model.sSortDir_0 == "asc")
{
list = list
.OrderBy(orderingFunction);
if (model.iSortCol_0 == 1 || model.iSortCol_0 == 3 || model.iSortCol_0 == 4)
{
list = list.OrderBy(dateOrderingFunction);
}
}
else
{
list = list
.OrderByDescending(orderingFunction);
if (model.iSortCol_0 == 1 || model.iSortCol_0 == 3 || model.iSortCol_0 == 4)
{
list = list.OrderByDescending(dateOrderingFunction);
}
}
}
}
else
{
var approveList = db.MembershipVacationApproves.ToList();
if (model.sSearch.IsNull())
{
list = approveList
.Where(i => i.MembershipID == UI.Helper.User.ID || i.MembershipVacation.MembershipID == UI.Helper.User.ID)
.Select(i => i.MembershipVacation)
.Distinct()
.Where(i => i.Type == type)
.Skip(model.iDisplayStart)
.Take(model.iDisplayLength);
}
else
{
list = approveList
.Where(i => i.MembershipID == UI.Helper.User.ID || i.MembershipVacation.MembershipID == UI.Helper.User.ID)
.Select(i => i.MembershipVacation)
.Distinct()
.Where(i =>
i.Type == type && (
i.Membership != null ? i.Membership.Username.Contains(model.sSearch, StringComparison.OrdinalIgnoreCase) : false
|| i.Membership.Department != null ? i.Membership.Department.Name.Contains(model.sSearch, StringComparison.OrdinalIgnoreCase) : false
|| i.StartDate.ToString().Contains(model.sSearch, StringComparison.OrdinalIgnoreCase)
|| i.EndDate.ToString().Contains(model.sSearch, StringComparison.OrdinalIgnoreCase)))
.Skip(model.iDisplayStart)
.Take(model.iDisplayLength);
}
}
List<string[]> result = new List<string[]>();
foreach (var item in list)
{
var waiting = item.MembershipVacationApproves.Count(i => i.State == UI.Vacation.ApproveState.Waiting) > 0;
var cancel = item.MembershipVacationApproves.Count(i => i.State == UI.Vacation.ApproveState.Cancel) > 0;
var approve = item.MembershipVacationApproves.Count(i => i.State == UI.Vacation.ApproveState.Approve) == item.MembershipVacationApproves.Count;
var edit = item.Membership.MembershipRelation != null ? item.Membership.MembershipRelation.OwnerID == UI.Helper.User.ID : false;
var canApprove = item.MembershipVacationApproves.Count(i => i.MembershipID == UI.Helper.User.ID) == 1;
StringBuilder name_link = new StringBuilder(),
durumu = new StringBuilder(),
islemler = new StringBuilder();
if (item.Membership.Staff != null)
{
name_link.Append("" + item.Membership.Username + "");
}
else
{
name_link.Append(item.Membership.Username);
}
if (!cancel)
{
if (approve)
{
if (DateTime.Now < item.StartDate)
{
durumu.Append("<small class='btn green-bg'>İstek onayladı.</small>");
}
else
{
if (DateTime.Now > item.EndDate)
{
durumu.Append("<small class='btn green'>Kişi izinden dönmüş.</small>");
}
else
{
durumu.Append("<small class='btn green'>Kişi izinde.</small>");
}
}
}
else
{
durumu.Append("<small class='btn orange'>İstek onaylanması için bekleniyor.</small>");
}
}
else
{
durumu.Append("<small class='btn red'>İstek iptal edilmiş</small>");
}
islemler.Append("<div class='btn-group'>");
islemler.Append("<a class='btn green' href='#' data-toggle='dropdown'><i class='icon-user'></i>İşlemler");
islemler.Append("<i class='icon-angle-down'></i></a>");
islemler.Append("<ul class='dropdown-menu'>");
islemler.Append("<li><a href='" + this.Url.Action("RequestDetail", "Vacation", new { id = item.ID }) + "' data-toggle='modal' data-target='#'><i class='icon-search'>");
islemler.Append("</i>İncele</a></li>");
/*if (User.IsInRole("İzin Onaylama") || edit)
{
islemler += "<li><a href='" + this.Url.Action("Request", "Vacation", new { id = item.ID }) + "'><i class='icon-search'>";
islemler += "</i>Düzenle</a></li>";
}*/
if (!(DateTime.Now > item.StartDate && approve) && canApprove)
{
islemler.Append("<li><i class='icon-ok'></i>Onayla</li>");
islemler.Append("<li><a href=" + this.Url.Action("DeclinePage", "Vacation", new { id = item.ID }) + " data-toggle='modal' data-target='#'><i class='icon-remove'></i>Onaylama</a></li>");
}
islemler.Append("</ul>");
islemler.Append("</div>");
result.Add(
new string[]
{
name_link.ToString(),
item.PostDate.ToString(),
item.Membership.Department != null ? item.Membership.Department.Name : string.Empty,
item.StartDate.ToString(),
item.EndDate.ToString(),
durumu.ToString(),
islemler.ToString()
});
}
var total = (DateTime.Now - startTime);
System.Diagnostics.Debug.WriteLine("total ms " + total.TotalMilliseconds);
return Json(new
{
sEcho = model.sEcho,
iTotalRecords = allEntries.Count(),
iTotalDisplayRecords = allEntries.Count(),
aaData = result
}, JsonRequestBehavior.AllowGet);
}
}
Worst part is last foreach process for make buttons and permissions
I would guess that you have an N+1 SQL query issue in your last foreach loop: you build list then trigger 5 SQL queries for each item in the list.
Advice to diagnose and fix:
Install MiniProfiler and enable database
profiling - then you'll be able to see which SQL queries are being
triggered by the request, and if you have any duplicate queries.
Make use of EntityFramework's Include method, to eager load related data when you're querying the items for list. This will save EF from having to issue separate duplicate queries within your foreach.
I have asked a question like this before, and the answer was great but the more I looked at my code the more confused I got, and after 10hrs my brain is shot and I'm in need of help. So all my content is loaded dynamically via Jquery's $.post and loaded into #content-container. Now I included my entire Jquery file to show you why I am getting so confused as how to get this to work without re-writing all the code. As you can see, and what I'm thinking, is that the history plugins such as BBQ, and history.js seem to be out of the question because I don't use anchor tags and the multitude of .live('click', funcition() { I have use different classes and id's for various reasons. I also believe that rules out using the hash and linking it to a single class via .trigger(), executing the AJAX(hope that makes sense). The only option I have left is actually kinda my question. Would it be possible to load the dynamic content into #content-container still using the $.post with $.load() or window.location and actually have the previous content loaded when the browser back button is clicked.
I greatly appreciate the help, really.....
$(document).ready(function() {
$(window).load(function () {
});
$('#map').hide();
$('#informational-container').hide();
$('.clickable').click(function(){
$('#map').hide();
});
function getTotalDealCount() {
$.post('../service/service.getTotalDealCount.php', {}, function(data) {
if(data.success) $('#deal-counter').append(data.results);
}, 'json');
return false;
}
function loadMap(lat, lon) {
var latlng = new google.maps.LatLng(lat, lon);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
}
function getLatLon(address, zipcode) {
$.post('../service/service.getLatLon.php', { address: address, zipcode: zipcode }, function(data) {
if(data.success) {
var res = data.results;
var coordinates = res.split('_');
loadMap(coordinates[0], coordinates[1]);
} else {
return false;
}
}, 'json');
return false;
}
function getAddressZipcode(id) {
$.post('../service/service.getAddressZipcode.php', { id: id }, function(data) {
if(data.success) {
var res = data.results;
var location = res.split('_');
getLatLon(location[0], location[1]);
} else {
return -1;
}
}, 'json');
return false;
}
$('#how-it-works').live('click', function() {
$('#content-container').load('../module/module.string.php #string-m1');
});
$('#why-post-a-deal').live('click', function() {
$('#content-container').load('../module/module.string.php #string-m2');
});
$('#who-are-we').live('click', function() {
$('#content-container').load('../module/module.string.php #string-m3');
});
$('#contact-us').live('click', function() {
$('#content-container').load('../module/module.string.php #string-m4');
});
$('#post-deal-img').live('click', function() {
$('#content-container').load('post.php');
});
$('.post-deal-inputs').live('click', function() {
$('.post-deal-inputs').live('click', function(e) {
$(this).val('');
$(this).removeClass('post-deal-inputs')
.addClass('post-deal-inputs-clicked');
});
});
$('#df5').live('click', function() {
$('#df7').val('');
$('#df7').hide();
});
$('#df6').live('click', function() {
$('#df7').show();
});
$('#post-how-to-link').live('click', function() {
apprise();
});
$('#terms').live('click', function() {
$('#content-container').load('../module/module.string.php #string-m5');
});
$('#disclaimer').live('click', function() {
$('#content-container').load('../module/module.string.php #string-m6');
});
$('#post-deal-button').live('click', function() {
var dealForm = $('#deal-form').serialize();
var company = $('#df1').val();
var description = $('#df2').val();
var zipcode = $('#df4').val();
var starts = $('#df7').val();
var ends = $('#df8').val();
if(company == '' || company == 'Company') {
apprise('A company name is required!');
return false;
}
if(description == '' || description == 'Deal') {
apprise('A deal is required!');
return false;
}
var swear = swearFilter(description);
if(swear != false) {
apprise('Please remove the naughty word `' + swear + '` from your deal.');
return false;
}
if(zipcode == '' || zipcode == 'Zipcode') {
apprise('A zipcode is required!');
return false;
}
if($('#df7').is(':visible') && typeof(ends) != 'undefined') {
var res = validateDate(starts);
if(res == false) {
apprise('Please select a valid start date!');
return false;
}
}
if(typeof(ends) != 'undefined') {
var res = validateDate(ends);
if(res == false) {
apprise('Please select a valid end date!');
return false;
}
}
if(ends == '') {
apprise('A deal end date is required!');
return false;
}
if($('#df7').is(':visible') && $('#df7').val() == '') {
apprise('If its not a one day sale a start date is required!');
return false
}
$.post('../service/service.postDeal.php', { dealForm: dealForm }, function(data) {
if(data.success == true) {
apprise('Your deal has been posted, thank you!');
window.location = '../root/index.php';
return true;
}
if(data.success == false) {
if(data.fail == 1) {
apprise('An error has occured and your deal has not been posted. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
return false;
}
if(data.fail == 2) {
apprise('The zipcode you supplied was not in our database. Please enter the city ' +
'and state/province in the following prompts to add your location.' , {'confirm':true}, function() {
insertNewLocation(zipcode);
});
}
if(data.fail == 3) {
apprise('A zipcode is required!');
}
}
}, 'json');
return false;
});
function validateDate(string) {
if(string.toLowerCase().indexOf('-') >= 0) {
var dateArray = string.split('-');
var year = dateArray[0], month = dateArray[1], day = dateArray[2];
if(year.length == 4 && month.length == 2 && day.length == 2) return true;
else return false;
}
return false;
}
function swearFilter(string) {
var ret = false;
var filter = [];
var stringArray = string.split(' ');
for(var i = 0; i < stringArray.length; i++) {
if(jQuery.inArray(stringArray[i], filter) > -1) {
ret = stringArray[i];
break;
}
}
return ret;
}
function insertNewLocation(zipcode) {
var city = '';
var state = '';
if (/[^a-zA-Z 0-9]+/g.test(zipcode)) {
apprise('The zipcode should contain only numbers, letters or both!');
return false;
}
apprise('Enter the name of the city:', {'input':true}, function(_city_) {
if(/[^a-zA-Z]+/g.test(_city_)) {
apprise('The city should contain only letters!');
return false;
}
city = _city_;
apprise('Enter the state in 2 letter abbreviated format:', {'input':true}, function(_state_) {
if (/[^a-zA-Z]+/g.test(_state_)) {
apprise('The state should contain only letters');
return false;
}
if(_state_.length > 2) {
apprise('The state should only be 2 letters in length');
}
state = _state_;
$.post('../service/service.insertNewLocation.php', { city: city, state: state, zipcode: zipcode }, function(data) {
if(data.success == true) {
apprise('Thank you, you may now submit you deal!');
return true;
}
if(data.success == false) {
if(data.fail == 1) {
apprise('An error has occured and your location has not been added to our database. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
return false;
}
if(data.fail == 2) {
apprise('A zipcode is required!');
return false;
}
}
}, 'json');
return false;
});
});
}
$('#search-type-button').live('click', function() {
var search = $('#search-type-text').val();
var keyword = $('#keyword-type-text').val();
if(search == '') {
apprise('A zipcode or city and state combo to search for deals in your area!');
return false;
}
if(keyword == 'Keyword') {
apprise('If you want to add a keyword to you deal, make sure its unique!');
return false;
}
$.post('../service/service.loadDealsByCityOrZipcode.php', { search: search, keyword: keyword }, function(data) {
if(data.success) {
$('#content-container').html(data.results);
return true;
}
if(data.success == false) {
if(data.fail == 1) {
apprise('An error has occured locating the deals. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
return false;
}
if(data.fail == 2) {
apprise('There are no deals within the zipcode you provided, be the first to add one!');
return false;
}
if(data.fail == 3) {
apprise('There are no deals matching the tag you supplied!');
return false;
}
if(data.fail == 4) {
apprise('A zipcode or city and state combo to search for deals in your area!');
return false;
}
}
}, 'json');
return false;
});
$('.deals-queried-deal').live('click', function() {
var id = this.id;
$('#comment-link').show();
$.post('../service/service.loadDealDescription.php', { id: id }, function(data) {
if(data.success == true) {
$('#content-container').html(data.results);
var res = getAddressZipcode(id);
if(res != -1) $('#map').show();
}
if(data.success == false) {
if(data.fail == 1) {
apprise('An error has occured loading the deal you selected. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
} else if(data.fail == 2) {
apprise('The deal you selected does not exist! ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
} else if(data.fail == 3) {
apprise('An error has occured loading the deal you selected. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
}
}
}, 'json');
return false;
});
$('.vote-down').live('click', function() {
var id = this.id;
var vote = 0;
$.post('../service/service.tallyVote.php', { id: id, vote: vote }, function(data) {
if(data.success == true) {
apprise('Thank you for your vote!');
return true;
}
if(data.success == false) {
if(data.fail == 1) {
apprise('An error has occured when voting for this deal. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
return false;
}
if(data.fail == 2) {
apprise('You have already voted for this deal!');
return false;
}
}
}, 'json');
return false;
});
$('.vote-up').live('click', function() {
var id = this.id;
var vote = 1;
$.post('../service/service.tallyVote.php', { id: id, vote: vote }, function(data) {
if(data.success == true) {
apprise('Thank you for your vote!');
return true;
}
if(data.success == false) {
if(data.fail == 1) {
apprise('An error has occured when voting for this deal. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
return false;
}
if(data.fail == 2) {
apprise('You have already voted for this deal!');
return false;
}
}
}, 'json');
return false;
});
$('#email-button').live('click', function() {
var emailAddress = $('.email-textbox').val();
var from = $('#from-textbox').val();
var message = $('#email-div').html();
var atpos = emailAddress.indexOf("#");
var dotpos = emailAddress.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= emailAddress.length) {
apprise('Please enter a valid email address!');
return false;
}
if(emailAddress == '') {
apprise('An email address is required!');
return false;
}
if(from == '') {
apprise('Your name is required!');
return false;
}
$.post('../service/service.emailDeal.php', { emailAddress: emailAddress, from: from, message: message}, function(data) {
if(data.success == true) {
apprise('The deal has been sent, we hope they enjoy it!');
return true;
}
if(data.success == false) {
if(data.fail == 1) {
apprise('An error has occured sending the email. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
return false;
}
if(data.fail == 2) {
apprise('An email address is required!');
return false;
}
}
}, 'json');
return false;
});
$('.comment-link').live('click', function() {
var id = this.id;
$.post('../service/service.loadComments.php', { id: id }, function(data) {
if(data.success == true) {
$('#content-container').html(data.results);
return true;
}
if(data.success == false) {
apprise('An error has occured retrieving the comments for this deal. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
return false;
}
}, 'json');
return false;
});
$('.post-comment-button').live('click', function() {
var id = this.id;
var comment = $('#comment-textarea').val();
var author = $('#post-comment-whois').val();
var swear = swearFilter(comment);
if(swear == true) {
apprise('Please remove the word "' + swear + '" from your comment.');
return false;
}
if(comment == '') {
apprise('Please fill out a comment first!');
return false;
}
$.post('../service/service.postComment.php', { id: id, comment: comment, author: author }, function(data) {
if(data.success == true) {
$.post('../service/service.loadComments.php', { id: id }, function(data) {
if(data.success == true) {
$('#content-container').html(data.results);
return true;
}
if(data.success == false) {
apprise('An error has occured retrieving the comments for this deal. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
return false;
}
}, 'json');
return false;
}
if(data.success == false) {
if(data.fail == 1) {
apprise('An error has occured while attempting to post your comment. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
return false;
}
if(data.fail == 2) {
apprise('Please fill out a comment first!');
return false;
}
}
}, 'json');
return false;
});
});`
Use history.js to pushState and then window.history.back()