I'm using QUnit and have a test script for a JQuery UI Widget:
define(
['jquery',
'knockout',
'../Widget/SearchPod/searchPod',
'jqueryui',
'jquery.ui.widget',
'../Widget/SearchPod/clr.searchPod'],
function ($, ko, searchPod) {
var checkSearchBy = function () {
test('check if select has Search By text', function () {
var expected = "Search By";
alert(searchPod.employees);//.checkSearchByWidget());
deepEqual(searchPod.employees, expected, "We expect drop down text to
display 'Search By' by default");
return 1;
});
};
return {
checkSearchBy: checkSearchBy
};
}
);
For some reason whenever I run the test script, an error occurs saying that the parameter searchpod above is undefined or null. The code of searchpod is below:
require(['jquery',
'knockout',
'jqueryui',
'jquery.ui.widget',
'domReady!',
'Widget/SearchPod/clr.searchPod',
'Widget/Listbox/clr.combobox'],
function ($, ko) {
$(document).ready(function () {
$("#search-pod").searchPod({
ready: function () {
var minimumLength = 2;
$("#search-message").hide();
//start
//end
var employees = [*some data*]
var leaves_filed = [*some data*]
var claims_filed = = [*some data*]
function sortData(prop, asc) {
data = data.sort(function (a, b) {
if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
});
}
//This is to display search messages depends on selected search type and
function validateCriteria(selectedType) {
var searchMessage = 'No values match search criteria';
if (selectedType == 'ssn') {
if ($("#searchBox").val().length > minimumLength) {
searchMessage = 'Must enter all 9 digits of SSN';
}
}
$("#search-message").text(searchMessage);
}
// Search pod items
var selectedType = 'lastname';
var data = employees;
// Apply the combobox widget
$("#searchBy").combobox({
ready: function () {
},
select: function () {
selectedType = $("option:selected", this).val();
switch (selectedType) {
case 'lastname':
return;
if (employees.length == 1) {
$("#loadingImage").css("display", "");
$("#searchBox").css("display", "none");
$.ajax({
url: "api/Dashboard/GetEmployeeListReport",
type: "GET",
processData: false,
success: function (result) {
employees.length = 0;
employees = result.dataSet.dataTable.row;
$("#loadingImage").css("display", "none");
$("#searchBox").css({ display: '' });
data = employees;
}
});
}
else { data = employees; }
minimumLength = 1;
break;
case 'ssn':
minimumLength = 10;
break;
case 'eeid':
if (employees.length == 1) {
$("#loadingImage").css("display", "");
$("#searchBox").css("display", "none");
$.ajax({
url: "api/Dashboard/GetEmployeeListReport",
type: "GET",
processData: false,
success: function (result) {
employees.length = 0;
employees = result.dataSet.dataTable.row;
$("#loadingImage").css("display", "none");
$("#searchBox").css({ display: '' });
data = employees;
minimumLength = employees[5].eeid.length;
}
});
}
else { data = employees; minimumLength =
employees[5].eeid.length; }
break;
case 'leave_number':
if (leaves_filed.length == 1) {
$("#loadingImage").css("display", "");
$("#searchBox").css("display", "none");
$.ajax({
url: "api/Dashboard/GetLeavesList",
type: "GET",
processData: false,
success: function (result) {
leaves_filed.length = 0;
leaves_filed = result.dataSet.dataTable.row;
$("#loadingImage").css("display", "none");
$("#searchBox").css({ display: '' });
data = leaves_filed;
minimumLength = leaves_filed[0].leaveNumber.length;
}
});
}
else { data = leaves_filed; minimumLength =
leaves_filed[0].leaveNumber.length; }
break;
case 'claim_number':
if (claims_filed.length == 1) {
$("#loadingImage").css("display", "");
$("#searchBox").css("display", "none");
$.ajax({
url: "api/Dashboard/GetClaimsList",
type: "GET",
processData: false,
success: function (result) {
claims_filed.length = 0;
claims_filed = result.dataSet.dataTable.row;
$("#loadingImage").css("display", "none");
$("#searchBox").css({ display: '' });
data = claims_filed;
minimumLength = claims_filed[10].claimNumber.length;
}
});
}
else { data = claims_filed; minimumLength =
claims_filed[10].claimNumber.length; }
break;
}
sortData(selectedType, true);
$('#searchBox').val('');
}
});
sortData(selectedType, true);
//This will hide search-message when backpress is pressed.
$('html').keyup(function (e) {
if (e.keyCode == 8) {
if ($("#searchBox").val().length < minimumLength) {
if ($("#search-message").show()) $("#search-message").hide();
}
}
return;
});
//Code for Making SSN AutoComplete
$('#searchBox').keyup(function () {
if (selectedType == "ssn" && $('#searchBox').val().length == 10) {
var rptParam = "?ssn=" + $('#searchBox').val();
var ssnData = [{ "ssn": "", "lastname": "" }];
$.ajax({
url: "api/Dashboard/GetSsnList" + rptParam,
type: "GET",
processData: false,
success: function (result) {
ssnData = result.dataSet.dataTable.row;
var ssnArray = [];
ssnArray.push(ssnData);
if (ssnArray.length > 0) {
$("#searchBox").autocomplete({
minLength: 10,
source: function (request, response) {
var searchField;
var filteredArray = $.map(ssnArray, function (item) {
if (item.ssn != null) {
searchField = item.ssn;
if (searchField.toLowerCase().indexOf
(request.term) == 0 || searchField.indexOf
(request.term) == 0) {
return item;
}
} else { return null; }
});
response(filteredArray);
},
focus: function (event, ui) {
var focusValue;
focusValue = ui.item.ssn;
$("#searchBox").val(focusValue);
return false;
},
select: function (event, ui) {
}
}).data("ui-autocomplete")._renderItem =
function (ul,item){
return $("<li>")
.append(displayFormat)
.appendTo(ul);
};
}
$('#searchBox').autocomplete("search");
}
});
}
return;
});
$("#searchBox").focus(function () {
if (selectedType == 'ssn') {
$("#searchBox").autocomplete();
$("#searchBox").autocomplete("destroy");
return;
}
var searchField;
$("#searchBox").autocomplete({
minLength: minimumLength,
source: function (request, response) {
var filteredArray = $.map(data, function (item) {
if (selectedType === 'lastname') {
searchField = item.lastname;
}
if (selectedType === 'ssn') {
return false;
}
if (selectedType === 'eeid') {
searchField = item.eeid;
}
if (selectedType === 'leave_number') {
searchField = item.leaveNumber;
}
if (selectedType === 'claim_number') {
searchField = item.claimNumber;
}
if (searchField.toLowerCase().indexOf(request.term) == 0 ||
searchField.indexOf(request.term) == 0) {
if (selectedType === 'ssn' && request.term.length < 4) {
return null;
}
return item;
}
else {
return null;
}
});
if (!filteredArray.length) {
$("#search-message").show();
validateCriteria(selectedType);
}
else {
$("#search-message").hide();
}
response(filteredArray);
},
focus: function (event, ui) {
var focusValue;
if (selectedType === 'lastname') {
focusValue = ui.item.lastname;
}
if (selectedType === 'eeid') {
focusValue = ui.item.eeid;
}
if (selectedType === 'leave_number') {
focusValue = ui.item.leaveNumber;
}
if (selectedType === 'claim_number') {
focusValue = ui.item.claimNumber;
}
$("#searchBox").val(focusValue);
return false;
},
create: function (event, ui) {
$(this).autocomplete("widget").addClass("search-results-list");
},
open: function (event, ui) {
$(".search-results-list li.ui-menu-item").addClass("search-results-item");
},
select: function (event, ui) {
//return false; // Cancel the select event
var focusValue;
if (selectedType === 'lastname') {
focusValue = ui.item.lastname;
// TODO: call a function here that will send the name of the report to show
$('#report-popup-dialog-overlay').show();
$('#report-popup-dialog').show();
}
if (selectedType === 'eeid') {
focusValue = ui.item.eeid;
}
if (selectedType === 'leave_number') {
focusValue = ui.item.leaveNumber;
$('#dynamictext').text('Leave Report for ' + focusValue);
$('#dynamicHeader').text('Leave Report');
}
if (selectedType === 'claim_number') {
focusValue = ui.item.claimNumber;
$('#dynamicHeader').text('Claim Report for ' + focusValue);
$('#dynamictext').html("Loading...");
//Need to make Ajax Call to get the report.
var parameter = "?claimNumber=" + focusValue;
$.ajax({
url: "api/ViewReport/GetClaimReport" + parameter,
type: "POST",
processData: false,
success: function (result) {
$('#dynamictext').html("");
$('#dynamictext').html(result);
}
});
}
return false;
}
})
.data("ui-autocomplete")._renderItem = function (ul, item) {
var displayFormat = "";
return $("<li>")
.append(displayFormat)
.appendTo(ul);
};
});
}
});
});
//Test helper functions
//2. checkSearchBy
function checkSearchBy() {
alert($('#searchBy').text());
return $('#searchBy').text();
}
return {
checkSearchByWidget: function () {
return checkSearchBy();
}
};
});
I've been at this for two days but cant seem to make the searchpod be seen by the test script above
Related
class ProductInfoDetailsViewModel {
constructor(parent, productInfoWindowId, inventoryId, productId, supplierId, store) {
this._parent = parent;
this._created = false;
this._productInfoWindowId = productInfoWindowId;
this._inventoryId = inventoryId;
this._productId = productId;
this._supplierId = supplierId;
this._store = store;
}
_getMvvmData(inventoryId, productId, supplierId) {
return new Promise(function (resolve, reject) {
$.ajax({
url: '/ProductRowInfoSite/GetInventoryControl',
data: {
'inventoryId': inventoryId,
'productId': productId,
'supplierId': supplierId,
},
dataType: 'json', // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
success: function (result) {
resolve(result);
},
error: function (jqXHR, textStatus, errorThrown) {
reject([jqXHR, textStatus, errorThrown]);
},
type: 'POST',
});
});
}
async create() {
let self = this;
let userStore = new UserStore();
//productInfoTextGrid
this._productInfoDetailsViewModel = kendo.observable({
value: {},
close: function () {
//$("#generalProductInfoWindow").data("kendoWindow").close();
//closeWindow();
},
not: function (value) {
return !this.get(value);
},
save: function (e) {
let productInfoTextGrid = $(self._productInfoWindowId + ' ' + '#productInfoTextGrid').data('kendoGrid');
/* productInfoTextGrid.saveChanges();*/
let orderUnitsGrid = $(self._productInfoWindowId + ' ' + '#orderUnitsGrid').data('kendoGrid');
let selectedRefHistProd = null;
try {
selectedRefHistProd = this.get('value.SelectedRefHistProd').ProductId;
} catch (error) {
// may be set to null and that's fine/TK.
}
var data = {
ProductId: self._productId,
InventoryId: self._inventoryId,
SupplierId: self._supplierId,
Fmean: this.get('value.Fmean'),
FMAD: this.get('value.FMAD'),
FTrend: this.get('value.FTrend'),
SelectedSeason: this.get('value.SelectedSeason').SeasonId,
MinQuantity: this.get('value.MinQuantity'),
SelectedOrderUnitNo: this.get('value.SelectedOrderUnit').UnitNo,
LeadTime: this.get('value.LeadTime'),
LeadTimeDeviation: this.get('value.LeadTimeDeviation'),
StockKeepInterest: this.get('value.StockKeepInterest'),
MaxLevel: this.get('value.MaxLevel'),
MinLevel: this.get('value.MinLevel'),
OrderQuantity: this.get('value.OrderQuantity'),
ReorderLevel: this.get('value.ReorderLevel'),
EnableManualSetRAndQ: this.get('value.EnableManualSetRAndQ'),
ForecastError: this.get('value.ForecastError'),
SelectedHistoryProductId: selectedRefHistProd,
};
var dataString = JSON.stringify(data);
$.ajax({
url: '/ProductRowInfoSite/SaveParameters',
data: {
data: dataString,
},
dataType: 'json',
// "jsonp" is required for cross-domain requests; use "json" for same-domain requests
success: function (result) {
// notify the data source that the request succeeded
//options.success(result);
self._store.dispatch({ type: ActionProductInfoWindow.Saving });
self._parent.refreshParentGrids();
},
error: function (result) {
displayAjaxError(result);
},
type: 'POST',
});
let userStore = new UserStore();
let finishSaved = userStore.translatedString('SOLOSupplier.ProductInfoWindows.FinishSaved');
displaySuccess(finishSaved);
productInfoTextGrid.saveChanges();
orderUnitsGrid.saveChanges();
},
recalc: function () {
var validator = $(self._productInfoWindowId).kendoValidator().data('kendoValidator');
var a = validator.validate();
},
products: new kendo.data.DataSource({
type: 'json',
serverFiltering: true,
pageSize: 100,
transport: {
read: function (options) {
$.ajax({
url: '/ProductRowInfoSite/GetProductInventoryList',
data:
{
'inventoryId': self._inventoryId,
'productId': self._productId,
'data': options.data,
},
//"filter": filter
dataType: 'json', // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
success: function (result) {
// notify the data source that the request succeeded
options.success(result.HistProducts);
},
error: function (result) {
// notify the data source that the request failed
options.error(result);
},
type: 'POST',
});
},
parameterMap: function (data, type) {
return kendo.stringify($.extend({ 'text': $(data.filter.filters).get(0).value }, data));
},
},
}),
isEnabled: true,
onValidate: function (e) {
console.log('onValidate');
let maxLevel = this.get('value.MaxLevel');
let minLevel = this.get('value.MinLevel');
let userStore = new UserStore();
let validationErrorMessage = userStore.translatedString('uctrlSupplierWeb.MaxLevelMinLevelWarning');
let validator = $(self._productInfoWindowId).kendoValidator({
messages: {
custom: validationErrorMessage,
},
rules: {
custom: function (input) {
if (input.is('[name=minLevelParameter]') && input.val() === '') {
return true;
} else if (input.is('[name=minLevelParameter]') && input.val() !== '' && maxLevel !== null) {
return maxLevel > minLevel;
}
if (input.is('[name=maxLevelParameter]') && input.val() === '') {
return true;
} else if (input.is('[name=maxLevelParameter]') && input.val() !== '' && minLevel !== null) {
return maxLevel > minLevel;
} else {
return true;
}
},
},
},
).data('kendoValidator');
if (validator.validate() === true) {
self._store.dispatch({ type: ActionProductInfoWindow.Changing });
} else {
self._store.dispatch({ type: ActionProductInfoWindow.Cancelling });
}
},
});
kendo.bind($(self._productInfoWindowId + ' ' + '#tabInventoryControl'), self._productInfoDetailsViewModel);
try {
let result = await self._getMvvmData(self._inventoryId, self._productId, self._supplierId);
self._productInfoDetailsViewModel.products.read();
self._productInfoDetailsViewModel.set('value', result);
if (result.UnitsOnOrderAfterLeadtime === true) {
if ($(self._productInfoWindowId + ' ' + '#valueUnitsOnOrder').data('kendoNumericTextBox')) {
let widget = $(self._productInfoWindowId + ' ' + '#valueUnitsOnOrder').data('kendoNumericTextBox');
widget.wrapper.find('input').addClass('lightRed');
}
}
if ($(self._productInfoWindowId + ' ' + '#minLevelParameterId').data('kendoNumericTextBox')) {
$(self._productInfoWindowId + ' ' + '#minLevelParameterId')
.data('kendoNumericTextBox')
.min(result.MinLevelDefault);
}
if ($(self._productInfoWindowId + ' ' + '#maxLevelParameterId').data('kendoNumericTextBox')) {
$(self._productInfoWindowId + ' ' + '#maxLevelParameterId')
.data('kendoNumericTextBox')
.min(result.MinLevelDefault);
}
var validator = $(self._productInfoWindowId).kendoValidator().data('kendoValidator');
validator.validate();
let element = $(self._productInfoWindowId);
window.kendo.ui.progress(element, false);
} catch ([jqXHR, textStatus, errorThrown]) {
displayAjaxError(jqXHR, textStatus, errorThrown);
productInfoDetailsViewModel.set('value', []);
window.kendo.ui.progress(element, false);
}
}
}
Saving edits in product info modal deletes used filters on products grid
if (productNo === null) {
let newFilter = await self._getFilterOnlyFromLocalStorage();
let totalFilter = $(self._gridId).data("kendoGrid").dataSource.filter();
totalFilter.filters.push.apply(totalFilter.filters, newFilter.filters);
$(self._gridId).data("kendoGrid").dataSource.filter(newFilter);
self._setPredefinedFilterButton(self);
}
}
This is the .js function:-
function SaveMergeOrderSetting(obj) {
debugger;
try {
if (obj != null) {
//Block multiple events
$(obj).addClass('disable-click');
}
var isOrderMergeConfigured = $("#ddlMergeOrderSettings").val();
var IsOrderMerge = false;
if (isOrderMergeConfigured == "True") {
IsOrderMerge = true;
}
else {
IsOrderMerge = false;
}
$.ajax({
async: false,
url: '/Store/CallOrderSettings/',
data: { IsOrderMergeConfigured1: IsOrderMerge },
success: function (data) {
obj = data;
if (obj == "True") {
closeConfirmPopup();
}
if (obj != null) {
//Block multiple events
$(obj).removeClass('disable-click');
}
}, error: function () {
if (obj != null) {
//Block multiple events
$(obj).removeClass('disable-click');
}
}
});
This is the class function:-
public bool CallOrderSettings(bool IsOrderMergeConfigured)
{
bool result = false;
try
{
}
catch
{}
return result;
}
I am looking to show a modal, I have my Modals as partial classes, so if you select the class .js-verify-songs it loads up the partial _VerifySong . If however there is an error, it should load up the error partial _ErrorMessage. And finally if you select .js-reject-song it should load _RejectSong partial.
Any idea how I would do this, please?
to show errors. Currently I have this in my Controller to handle errors:
public partial class SongsManagementController : BaseController
{
private const string NoDataFound = "No data found.";
private const string InvalidDataPosted = "Invalid data posted";
private const string InvalidRequest = "Invalid request.";
private const string VerificationFailedUnexpectedError = "The following song failed to verify due to an unexpected error, please contact RightsApp support.";
private const string ConcurrencyError = "The following song failed to verify as another user has since changed its details.";
[HttpPost]
[Route("VerifyNewSongs")]
[AuthorizeTenancy(Roles = "super,administrator")]
public async Task<ActionResult> VerifyNewSongs(List<VerifySongViewModel> verifySongViewModels)
{
// Not AJAX method - refuse
if (!Request.IsAjaxRequest())
return RedirectToAction("NewSongs", "SongsManagement");
if (verifySongViewModels.NullOrEmpty())
{
// return error;
return Json(new JsonBaseModel
{
success = false,
message = InvalidRequest,
data = null,
errors = new List<string>
{
InvalidDataPosted
}
});
}
foreach (var verifySong in verifySongViewModels)
{
if (verifySong.WorkId == default(Guid) || verifySong.RowVersion == default(Guid))
{
return Json(new JsonBaseModel
{
success = false,
message = InvalidDataPosted,
data = null,
errors = new List<string>
{
$"Invalid data posted for following song.",
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
var work = await _artistAccountService.GetWorkGraphAsync(verifySong.WorkId, includeWriterAmendments: true);
if (work == default(WorkGraphModels.Work))
{
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
$"No data found for following song.",
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
if (work.VerifiedState != Domain.Enumerators.VerifiedStateType.NotVerified)
{
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
$"Song already verified.",
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
work.RowVersion = verifySong.RowVersion;
var workAndAmendment = new WorkGraphModels.WorkAndAmendment
{
Original = work,
Amendment = null
};
var verifiedState = await _artistAccountService.VerifyWorkGraphAsync(workAndAmendment, GetLoggedUserId());
if (!verifiedState.ValidationErrors.NullOrEmpty())
{
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
VerificationFailedUnexpectedError,
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
else if (!verifiedState.DatabaseErrors.NullOrEmpty())
{
if (!verifiedState.FatalException)
{
// concurrency exception
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
ConcurrencyError,
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
else
{
// fatal
return Json(new JsonBaseModel
{
success = false,
data = null,
errors = new List<string>
{
VerificationFailedUnexpectedError,
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
}
}
return Json(new JsonBaseModel
{
success = true,
message = "All songs verified successfully."
});
}
};
}
This is my Main View:
Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_SentricLayout.cshtml";
var actionName = ViewContext.RouteData.Values["Action"].ToString();
#* calc full account code *#
var fullAccountCode = Model.WorkUniqueCode;
ViewBag.Title = "New Songs";
}
#section scripts {
#Scripts.Render("~/bundles/jqueryajaxval")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/datetimepicker")
<script language="javascript" type="text/javascript">
#* DOM ready? *#
$(function () {
addTableStylingScripts();
var selectFormDiv = $('.catalogSelector');
selectFormDiv.hide();
$(".records-selected").hide();
// clear all filter boxes and reset search.
$("#btnClear").click(function()
{
$("#newSongsSearch").find(':input').each(function ()
{
if (this.type === "text")
{
$(this).val("");
}
});
$("#btnSearch").click();
});
#* edit catalogue button *#
$('#changeCat').click(function () {
$('#errorContainer').hide();
var label = $('#catLabel');
if (label.is(":visible")) {
label.hide();
selectFormDiv.show();
$('#changeCat').addClass("active");
} else {
label.show();
selectFormDiv.hide();
$('#changeCat').removeClass("active");
}
});
#* edit dropdown *#
$("#catalogueSelect").on("change", function () {
#* change display on select change *#
$('#errorContainer').hide();
$('#catLabel').show();
selectFormDiv.hide();
$('#changeCat').removeClass("active");
#* set up ajax post to controller *#
var model = {
AccountCode: '#fullAccountCode',
CurrentAccountId: $('#currentAccountId').val(),
CurrentRowVersion: $('#currentRowVersion').val(),
NewCatalogueId: $('#catalogueSelect option:selected').val(),
Action: '#actionName'
};
$.ajax({
url: '#Url.Action("ChangeCatalogue", "ArtistAccount")',
data: JSON.stringify(model),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
#* ajax worked *#
if (result.ChangeStatus === "Success")
{
var newSelected = $('#catalogueSelect option:selected').text();
$('#catLabel').html(newSelected);
#* update dropdown context *#
var newSelectedId = $('#catalogueSelect option:selected').val();
$('#currentCatalogue').val(newSelectedId);
#* update rowversion *#
var newRowVersion = result.OldOrNewRowVersion;
$('#currentRowVersion').val(newRowVersion);
}
else
{
$('#errorContainer').show();
$('#errorMessage').html(result.ErrorMessage);
#* return downdown context *#
var currentCatId = $('#currentCatalogue').val();
$("#catalogueSelect").val(currentCatId);
$('#catalogueSelect').select2({ width: '180px', dropdownAutoWidth: true });
}
},
error: function () {
#* failed *#
$('#errorContainer').show();
$('#errorMessage').html('There was a server error, please contact the support desk on (+44) 0207 099 5991.');
#* return downdown context *#
var currentCatId = $('#currentCatalogue').val();
$("#catalogueSelect").val(currentCatId);
$('#catalogueSelect').select2({ width: '180px', dropdownAutoWidth: true });
}
});
});
function loadPartialPage(url) {
$('.spinnerOverlay').removeClass('hide');
$.ajax({
url: url,
type: 'GET',
cache: false,
success: function (result) {
$('.spinnerOverlay').addClass('hide');
$('#tableContainer').html(result);
addBootstrapTooltips("#tableContainer");
}
});
}
function getSelectedWorks() {
var selectedWorks = $(".individual:checked");
var works = [];
$.each(selectedWorks, function (key, value) {
works.push(getSelectedWork(this));
});
return works;
}
// verify songs in bulk
$(document).on("click", ".js-verify-songs", function (e) {
e.preventDefault();
var works = getSelectedWorks();
verifySongs(works);
});
// reject songs in bulk
$(document).on("click", ".js-reject-songs", function (e) {
e.preventDefault();
var works = getSelectedWorks();
});
function getSelectedWork(element) {
var work = new Object();
work.WorkId = getRowData(element, "id");
work.RowVersion = getRowData(element, "rowversion");
work.UniqueCode = getRowData(element, "uniqueworkid");
work.SongTitle = getRowData(element, "songtitle");
return work;
}
// verify one song
$(document).on("click", ".js-verify-song", function (e) {
e.preventDefault();
var works = [];
works.push(getSelectedWork(this));
verifySongs(works);
});
// reject one song
$(document).on("click", ".js-reject-song", function (e) {
e.preventDefault();
var works = [];
works.push(getSelectedWork(this));
});
function verifySongs(songs) {
$('.spinnerOverlay').removeClass('hide');
$.ajax({
url: '#Url.Action("VerifyNewSongs", "SongsManagement")',
data: JSON.stringify(songs),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
$('.spinnerOverlay').addClass('hide');
if (result.success) {
loadPartialPage($(".paginate_button.active a").attr("href"));
}
},
error: function(error) {
$('.spinnerOverlay').addClass('hide');
}
});
}
#* Pagination Async Partial Handling *#
$(document).on("click",
"#indexPager a",
function() {
if ($(this).parent().hasClass('disabled') || $(this).parent().hasClass('active'))
return false;
loadPartialPage($(this).attr("href"));
return false;
});
$(document).on("change",
"#pageSizeSelector",
function() {
var selectedValue = $(this).val();
loadPartialPage(selectedValue);
return false;
});
#* Sorting Async Partial Handling *#
$(document).on("click",
"#tableHeader a",
function()
{
loadPartialPage($(this).attr("href"));
return false;
});
});
// Ensure that after paging and sorting ajax calls we re-bind
// the change event and hide the record count label.
$(document).ajaxComplete(function() {
$(".records-selected").hide();
$(".individual").on("change", determineActionButtonAvailability);
$(".selectall").click(function () {
$(".individual").prop("checked", $(this).prop("checked"));
determineActionButtonAvailability();
});
});
// Search functions
$('.searchDivider').click(function (e) {
$('#searchFields').slideToggle();
var isSearchShown = $(this).find('.caret').hasClass("caret-up");
if (isSearchShown) {
$(this).children('span').replaceWith('<span class="bg-white">Search <b class="caret"></b></span>');
} else {
$(this).children('span')
.replaceWith('<span class="bg-white">Search <b class="caret caret-up"></b></span>');
}
});
$(".searchArea input:text").keypress(function (e) {
if (e.which === 13) {
e.preventDefault();
$("#btnSearch").click();
}
});
$(window).resize(function () {
if ($(window).width() >= 1024) {
$('#searchFields').show();
}
});
$(".searchArea input:text").keypress(function (e) {
if (e.which === 13) {
e.preventDefault();
$("#btnSearch").click();
}
});
// Checks individual checkboxes and displays the count
$(".individual").on("change", determineActionButtonAvailability);
$(".selectall").click(function () {
$(".individual").prop("checked", $(this).prop("checked"));
determineActionButtonAvailability();
});
//Disable Top Verify Button if two or more checkboxes are selected.
$('.verify-btn').prop('disabled', true);
//Disable Action Button in the columns when more than one checkbox is selected
$('.table-btn').prop('disabled', false);
$(".individual").on("click", function () {
if ($(".individual:checked").length > 1) {
$('.table-btn').prop('disabled', true);
$('.verify-btn').prop('disabled', false);
}
else {
$('.table-btn').prop('disabled', false);
$('.verify-btn').prop('disabled', true);
}
});
// When one or more works are selected, will enable the top action menu.
// Will disable when none selected.
function determineActionButtonAvailability() {
if ($(".individual:checked").length > 1) {
$(".records-selected").show();
$("#selected").text($(".individual:checked").length);
$("#total").text($(".individual").length);
$(".verify-btn").prop('disabled', false);
if ($(".individual:checked").length > 1) {
}
}
else {
$(".records-selected").hide();
$('.table-btn').prop('disabled', false);
$(".verify-btn").prop('disabled', true);
}
}
// Enforce only numeric input in the Unique Id search textbox.
$(document).on("keydown", ".uniqueCodefield", function (e) {
var key = window.event ? e.keyCode : e.which;
var currentVal = $('.uniqueCodefield').val();
if (key === 8 || key === 9 || key === 13 || key === 37 || key === 39 || key === 35 || key === 36 || key === 46) {
return true;
} else if (key === 13) {
$('#newSongsSearch').validate();
if ($('#newSongsSearch').valid()) {
return true;
}
return false;
}
else if ((key < 48 || key > 57) && (key < 93 || key > 105)) {
return false;
} else if (currentVal.length >= 10) {
return false;
} else {
return true;
}
});
#* Wire up the Search button click to perform an AJAXified search *#
$(document).on("click", "#btnSearch", function (e) {
e.preventDefault();
// Only perform the search if the search criteria is valid.
if (!$('#newSongsSearch').valid()) {
return false;
}
$('.spinnerOverlay').removeClass('hide');
var model = {
SearchModel: {
WorkUniqueCode: $('#SongCode').val(),
SongTitle: $('#SongTitle').val(),
CatalogueUniqueCode: $('#CatalogueCode').val(),
CatalogueName: $('#CatalogueName').val(),
AccountUniqueCode: $('#AccountCode').val(),
AccountName: $('#AccountName').val()
}
};
$.ajax({
url: '#Url.Action("SearchNewSongs", "SongsManagement")',
data: JSON.stringify(model),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
$('#tableContainer').html(result);
addBootstrapTooltips("#tableContainer");
}
});
return false;
});
#* Wire up the Search button click to perform an AJAXified search *#
$(document).on("click", "#btnSearch", function (e) {
e.preventDefault();
$('.spinnerOverlay').removeClass('hide');
var model = {
SearchModel : {
Name: $('#ContractNameSearch').val(),
ContractType: $('#ContractTypeSearch').val(),
CreatedBy: $('#CreatedBySearch').val(),
DateFrom : $('#DateFromSearch').val(),
DateTo : $('#DateToSearch').val()
}
};
$.ajax({
url: '#Url.Action("SearchContracts", "ClientSetup")',
data: JSON.stringify(model),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
$('#tableContainer').html(result);
addBootstrapTooltips("#tableContainer");
}
});
return false;
});
</script>
#Scripts.Render("~/bundles/searchusers-autosuggest")
}
#section additionalStyles {
#Styles.Render("~/plugins/datatables/media/css/cssDatatables")
}
<article class="row">
<h1 class="pageTitle artistHeader fw200 mb20 mt10">#ViewBag.Title</h1>
<div class="col-md-12">
<div class="panel panel-visible">
#Html.Partial("_NewSongsSearch", Model)
</div>
</div>
<div class="col-md-12">
<div class="panel panel-visible" id="tableContainer">
#Html.Partial("_NewSongsList", Model)
</div>
</div>
</article>
I am unsure though how I would show a list of error in my error partial view. Also how do you load a partial view with Ajax?
Currently you click verify and it loads the spinner, but I would like to load a partial view which is a modal. I’ve used partials because it’s what was decided. I’m just unsure how to get them to load using Ajax.
I have autocomplete input in my View.
Here is script, how I handle it
$(targetSelector).each(function() {
$(this)
.autocomplete({ delay: 10, minLength: 0, source(request, response) {
$(this.element[0]).attr("data-req-term", request.term);
$.ajax({
url: $(this.element[0]).attr("data-source"),
dataType: "json",
data: {
term: request.term
},
success(data) {
console.dir(data);
const results = [];
$.map(data.cities, function(value, key) {
results.push(value);
return $.map(value.airports, (value2, key2) =>
results.push(value2)
);
});
$.map(data.airports, (value, key) => results.push(value));
return response(results);
},
error() {
return response([]);
}
});
return null;
}, focus(event, ui) {
return false;
}, select(event, ui) {
const qel = $(event.currentTarget);
qel.val(ui.item.fullname);
$(qel.attr("data-id-element")).val(ui.item.id);
return false;
}
})
.data("ui-autocomplete")._renderItem = function(ul, item) {
return create_autocomplete_item($(this.element[0]), ul, item);
};
if (enableAutocompleteSelect) {
$(targetSelector).on("autocompleteselect",
function() {
if ($(this)[0].id.indexOf("origin") !== -1) {
const id = $(this)[0].id.split("_")[2];
$(`#search_legs_${id}_destination_text`).focus();
}
});
}
$(targetSelector).focus(function() {
$(this).keydown();
});
$(targetSelector).on("blur", function() {
const value = $(this).val() as string;
if (value.trim() == "") {
$(this).val("");
}
});
});
}
This function is using to get data for autocomplete. Aтв show airports and cities.
And here is answer from server, that I get.
I need to populate also hotels to autocomplete results.
How I can do this?
I can get values for Hotel just add this line
$.map(data.hotels, (value,key)=> results.push(value));
I am doing a four API calls(for twitter,facebook,instagram,youtube) on selecting brand name and get data and set the response to different div.
When if i select first brand say "ford" and request made by using ajax asynchronous call, on between request if i select other brand,then previous made request is aborted and second one get processed.
First Ajax calls is aborted and second request was run but between abort process,my dropdown box get unresponsive until all request get aborted.
Sample code :
$(document).ready(function ()
{
var cblcurrentRequest = null;
var currentRequest = null;
var twcurrentRequest = null;
var fbcurrentRequest = null;
var igcurrentRequest = null;
var ytcurrentRequest = null;
var firsttwcurrentRequest = null;
var firstfbcurrentRequest = null;
var firstigcurrentRequest = null;
var firstytcurrentRequest = null;
load_session();//load access key on session
$('#brands').prop('disabled', 'disabled');
$('#selcategory').change(function () {
$('.loader_cmn').show();
$("#brands").select2("val", null);
$('#brands').append('<option value=" ">Select Brand Name</option>');
$('#brands').prop('disabled', true);
var categoryID = this.value;
if (categoryID != "") {
currentRequest = $.ajax({url: baseurl + 'admin/Adminhome/getCategoryListByIdWithLogin/' + categoryID, type: 'post', data: '',
beforeSend: function () {
var msg = "<center><b>Please select brand</b></center>";
$('#tw').html(msg);
$('#fb').html(msg);
$('#inst').html(msg);
$('#yt').html(msg);
hide_loader();
if (currentRequest != null) {
currentRequest.abort();
}
if (twcurrentRequest != null) {
twcurrentRequest.abort();
}
if (fbcurrentRequest != null) {
fbcurrentRequest.abort();
}
if (igcurrentRequest != null) {
igcurrentRequest.abort();
}
if (ytcurrentRequest != null) {
ytcurrentRequest.abort();
}
if (firsttwcurrentRequest != null) {
firsttwcurrentRequest.abort();
}
if (firstfbcurrentRequest != null) {
firstfbcurrentRequest.abort();
}
if (firstigcurrentRequest != null) {
firstigcurrentRequest.abort();
}
if (firstytcurrentRequest != null) {
firstytcurrentRequest.abort();
}
}
}).done(function (res)
{
$("#brands").empty();
$('#brands').append('<option value="" selected="">Select Brand Name</option>');
var obj = JSON.parse(res);
$.each(obj, function (i, item) {
$('#brands').append('<option value="' + obj[i].BrandID + '">' + obj[i].BrandName + '</option>');
});
$('.loader_cmn').hide();
$('#brands').prop('disabled', false);
}).fail(function (res) {
});
}
});
$('#display_alert').show();
function load_session() {
$.ajax({url: baseurl + 'Login/set_accesskeys', type: 'post', async: false, cache: true, data: ''}).done(function (res)
{
setTimeout(2000);
}).fail(function (res) {
});
}
var msg = "<center><b>Please select brand</b></center>";
if ($("#brands").val() === "") {
$('#tw').html(msg);
$('#fb').html(msg);
$('#inst').html(msg);
$('#yt').html(msg);
$('#yelp').html(msg);
} else {
var brand_id = $.trim($("#brands").val());
load_social_feeds(brand_id);
}
$("#brands").change(function () {
$(window).scrollTop(0);
var brand_id = $.trim(this.value);
load_social_feeds(brand_id);
});
function hide_loader()
{
$('#loader_tw').hide();
$('#loader_fb').hide();
$('#loader_inst').hide();
$('#loader_yt').hide();
}
function getChannelBrandlistJson(brand_id)
{
var channelBrandList;
var facebookBrandName;
var twitterBrandName;
var youtubeBrandName;
var instagramBrandName;
var yelpBrandName;
cblcurrentRequest = $.ajax({url: baseurl + 'Login/getChannelBrand/' + brand_id, type: 'post', async: false, cache: true, data: '',
beforeSend: function () {
if (cblcurrentRequest != null) {
cblcurrentRequest.abort();
}
if (firsttwcurrentRequest != null) {
firsttwcurrentRequest.abort();
}
if (firstfbcurrentRequest != null) {
firstfbcurrentRequest.abort();
}
if (firstigcurrentRequest != null) {
firstigcurrentRequest.abort();
}
if (firstytcurrentRequest != null) {
firstytcurrentRequest.abort();
}
if (twcurrentRequest != null) {
twcurrentRequest.abort();
}
if (fbcurrentRequest != null) {
fbcurrentRequest.abort();
}
if (igcurrentRequest != null) {
igcurrentRequest.abort();
}
if (ytcurrentRequest != null) {
ytcurrentRequest.abort();
}
}
}).done(function (res)
{
channelBrandList = JSON.parse(res);
facebookBrandName = channelBrandList['FacebookChannel'];
twitterBrandName = channelBrandList['TwitterChannel'];
youtubeBrandName = channelBrandList['YoutubeChannel'];
instagramBrandName = channelBrandList['InstagramChannel'];
YelpBrandName = channelBrandList['YelpChannel'];
$('#facebookchannel').val(facebookBrandName);
console.log(facebookBrandName);
$('#twitterchannel').val(twitterBrandName);
console.log(twitterBrandName);
$('#youtubechannel').val(youtubeBrandName);
console.log(youtubeBrandName);
$('#instagramchannel').val(instagramBrandName);
console.log(instagramBrandName);
$('#yelpchannel').val(YelpBrandName);
console.log(yelpBrandName);
}).fail(function (res) {
});
}
function Twfeed(brand_name)
{
var indexCount = 2;//used to calls the all three month post
$('#twContainer').scrollTop(0);
$('#twContainer').perfectScrollbar('update');
loader_show();
// setTimeout(function wait() {
twcurrentRequest = $.ajax({url: baseurl + 'Twfeed/get_Twfeed/' + brand_name + '/' + indexCount, type: 'post', data: '',
beforeSend: function () {
if (twcurrentRequest != null) {
twcurrentRequest.abort();
}
}
}).done(function (res)
{
if (res != null && res.trim() != '')
{
setcontent(res);
}
}).fail(function (res) {
});
//}, 1000);
}
function FirstTwfeed(brand_name)
{
var indexCount = 1; //used to calls the first three post
$('#twContainer').scrollTop(0);
$('#twContainer').perfectScrollbar('update');
loader_show();
// setTimeout(function wait() {
firsttwcurrentRequest = $.ajax({url: baseurl + 'Twfeed/get_Twfeed/' + brand_name + '/' + indexCount, type: 'post', data: ''}).done(function (res)
{
if (res != null && res.trim() != '')
{
setcontent(res);
Twfeed(brand_name);
}
}).fail(function (res) {
});
// }, 1000);
}
function Fbfeed(brand_name)
{
// load_session();
var indexCount = 2;
$('#fbContainer').scrollTop(0);
$('#fbContainer').perfectScrollbar('update');
$('#loader_fb').show();
//setTimeout(function wait() {
fbcurrentRequest = $.ajax({url: baseurl + 'Fbfeed/get_Fbfeed/' + brand_name + '/' + indexCount, type: 'post', data: '',
beforeSend: function () {
if (fbcurrentRequest != null) {
fbcurrentRequest.abort();
}
}
}).done(function (res)
{
if (res != null && res.trim() != '')
{
$('#fb').html(res);
$('#loader_fb').hide();
}
}).fail(function (res) {
});
//}, 1000);
}
function FirstFbfeed(brand_name)
{
// load_session();
var indexCount = 1;
$('#fbContainer').scrollTop(0);
$('#fbContainer').perfectScrollbar('update');
$('#loader_fb').show();
//setTimeout(function wait() {
firstfbcurrentRequest = $.ajax({url: baseurl + 'Fbfeed/get_Fbfeed/' + brand_name + '/' + indexCount, type: 'post', data: '',
}).done(function (res)
{
if (res != null && res.trim() != '')
{
$('#fb').html(res);
$('#loader_fb').hide();
Fbfeed(brand_name);
}
}).fail(function (res) {
});
//}, 1000);
}
function Instfeed(brand_name)
{
//load_session();
var indexCount = 2;
$('#instaContainer').scrollTop(0);
$('#instaContainer').perfectScrollbar('update');
$('#loader_inst').show();
// setTimeout(function wait() {
igcurrentRequest = $.ajax({url: baseurl + 'Igfeed/get_Igfeed/' + brand_name + '/' + indexCount, type: 'post', data: '',
beforeSend: function () {
if (igcurrentRequest != null) {
igcurrentRequest.abort();
}
}
}).done(function (res)
{
if (res != null && res.trim() != '')
{
$('#inst').html(res);
$('#loader_inst').hide();
}
}).fail(function (res) {
});
//}, 1000);
}
function FirstInstfeed(brand_name)
{
//load_session();
var indexCount = 1;
$('#instaContainer').scrollTop(0);
$('#instaContainer').perfectScrollbar('update');
$('#loader_inst').show();
// setTimeout(function wait() {
firstigcurrentRequest = $.ajax({url: baseurl + 'Igfeed/get_Igfeed/' + brand_name + '/' + indexCount, type: 'post', data: '',
}).done(function (res)
{
if (res != null && res.trim() != '')
{
$('#inst').html(res);
$('#loader_inst').hide();
Instfeed(brand_name);
}
}).fail(function (res) {
});
//}, 1000);
}
function Ytfeed(brand_name)
{
//load_session();
var indexCount = 2;
$('#ytContainer').scrollTop(0);
$('#ytContainer').perfectScrollbar('update');
$('#loader_yt').show();
//setTimeout(function wait() {
ytcurrentRequest = $.ajax({url: baseurl + 'Ytfeed/get_Ytfeed/' + brand_name + '/' + indexCount, type: 'post', data: '',
beforeSend: function () {
if (ytcurrentRequest != null) {
ytcurrentRequest.abort();
}
}
}).done(function (res)
{
if (res != null && res.trim() != '')
{
$('#yt').html(res);
$('#loader_yt').hide();
}
}).fail(function (res) {
});
// }, 1000);
}
function FirstYtfeed(brand_name)
{
//load_session();
var indexCount = 1;
$('#ytContainer').scrollTop(0);
$('#ytContainer').perfectScrollbar('update');
$('#loader_yt').show();
//setTimeout(function wait() {
firstytcurrentRequest = $.ajax({url: baseurl + 'Ytfeed/get_Ytfeed/' + brand_name + '/' + indexCount, type: 'post', data: '',
}).done(function (res)
{
if (res != null && res.trim() != '')
{
$('#yt').html(res);
$('#loader_yt').hide();
Ytfeed(brand_name);
}
}).fail(function (res) {
});
// }, 1000);
}
function setcontent(res) {
$('#tw').html(res);
loader_hide();
}
function loader_show() {
$('#loader_tw').show();
}
function loader_hide() {
$('#loader_tw').hide();
}
function load_social_feeds(brand_id) {
//load_session();
getChannelBrandlistJson(brand_id);
//load_session();
//setTimeout(function wait() {
$('#tw').html("");
$('#fb').html("");
$('#inst').html("");
$('#yt').html("");
$('#yelp').html("");
//var brand_name = $.trim($("#brands").val());
//alert('load method');
if (brand_id !== "") {
$(".chanel input[type=checkbox]:checked").each(function ()
{
//alert("Id: " + $(this).attr("id") + " Value: " + $(this).val() + " Checked: " + $(this).is(":checked"));
$exp = parseInt($(this).val());
switch ($exp) {
case 1:
$('#twsection').show();
var twitterBrandName = $('#twitterchannel').val();
console.log('twitterBrandName-' + twitterBrandName);
FirstTwfeed(twitterBrandName);
// Twfeed(twitterBrandName); // Load Twitter
break;
case 2:
$('#fbsection').show();
var facebookBrandName = $('#facebookchannel').val();
console.log('facebookBrandName-' + facebookBrandName);
FirstFbfeed(facebookBrandName);
// Fbfeed(facebookBrandName); // Load Facebook
break;
case 3:
$('#instsection').show();
var instagramBrandName = $('#instagramchannel').val();
console.log('instagramBrandName-' + instagramBrandName);
FirstInstfeed(instagramBrandName); // Load Instagram
//Instfeed(instagramBrandName); // Load Instagram
break;
case 4:
$('#ytsection').show();
var youtubeBrandName = $('#youtubechannel').val();
console.log('youtubeBrandName-' + youtubeBrandName);
FirstYtfeed(youtubeBrandName); //Load Youtube
//Ytfeed(youtubeBrandName); //Load Youtube
break;
}
});
} else {
$('#tw').html(msg);
$('#fb').html(msg);
$('#inst').html(msg);
$('#yt').html(msg);
$('#yelp').html(msg);
}
}
});
I am using Codeigniter framework for server script.ajax call request to my controller and controller all required API Libraries and send back HTML response back to ajax.
Please suggest,if i am missing anything.
Thanks,