UI Unresponsive when we jquery ajax abort called - javascript

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,

Related

When I edited directly in the grid instead of the modal at the right the filter never drops but when I edit in modal and save the filter dropped

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);
}
}

Only one alert for multiple execution in Ajax

I am working rails application.i need to get status of the each selected device.I am able to achieve this but after executing i am putting alert "Successfully created execution record".For every mac selection it is showing alert message.I need to give one alert in end of execution.I am calling display_result in call_endpoint method.Since it is an Ajax call,it is giving alert for every execution.i don't how to limit to single alert for this.
function display_result() {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
alert('Successfully created execution record");
}
});
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 0; i < m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result();
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
Below is changed code..
Copy below code as it is.
function display_result(total,current) {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
if(total == current)
{
alert('Successfully created execution record");
}
}
});
}
}
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 1; i <= m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result(m,i);
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
}
result and mac is not defined in display_result function. result appears intended to be the resulting value of jQuery promise object returned from $.ajax(). Am not certain what mac is indented to be.
You can substitute $.when() and $.map() for for loop, return a jQuery promise object from call_endpoint(), include error handling, chain .then() to call_endpoint() call to execute alert() once.
function call_endpoint() {
return $.when.apply($, $.map(values, function(macAdd) {
return $.ajax().then(display_result)
}))
}
callEnpoint()
.then(function() {
alert('Successfully created execution record');
}, function(jqxhr, textStatus, errorThrown) {
console.error(errorThrown)
});
function display_result(reuslt) {
..
if (if (result["response"].status == "200")) {
return $.ajax() // remove `alert()` from `success`
}
return;
}

Event not working in Jquery

I have this code:
this.$root.find(".thread-vote-item").click( function() {
var current_value = self.getCurrentValue();
if(current_value !== null || current_value !== '' ) {
self.enableButton(current_value);
}
self.disableButton($(this).data('label'));
$.ajax({
url: $("#base-url").val() + '/thread/submit-vote',
type: 'post',
data: {thread_id: self.thread_id, vote: current_value},
success: function(data) {
if(data) {
self.setCurrentValue(current_value);
self.triggerChangedVoteEvent();
} else {
}
}
});
return true;
});
The click event does not work
but if i change to become lik ethis
$(".thread-vote-item").click( function() {
var current_value = self.getCurrentValue();
if(current_value !== null || current_value !== '' ) {
self.enableButton(current_value);
}
self.disableButton($(this).data('label'));
$.ajax({
url: $("#base-url").val() + '/thread/submit-vote',
type: 'post',
data: {thread_id: self.thread_id, vote: current_value},
success: function(data) {
if(data) {
self.setCurrentValue(current_value);
self.triggerChangedVoteEvent();
} else {
}
}
});
return true;
});
It works. What is the difference between $(selector) and $(selector).find();
this.$root comes from another $(selector).find

Does jQuery.ajax() not always work? Is it prone to miss-fire?

I have an $.ajax function on my page to populate a facility dropdownlist based on a service type selection. If I change my service type selection back and forth between two options, randomly the values in the facility dropdownlist will remain the same and not change. Is there a way to prevent this? Am I doing something wrong?
Javascript
function hydrateFacilityDropDownList() {
var hiddenserviceTypeID = document.getElementById('<%=serviceTypeID.ClientID%>');
var clientContractID = document.getElementById('<%=clientContractID.ClientID%>').value;
var serviceDate = document.getElementById('<%=selectedServiceDate.ClientID%>').value;
var tableName = "resultTable";
$.ajax({
type: 'POST',
beforeSend: function () {
},
url: '<%= ResolveUrl("AddEditService.aspx/HydrateFacilityDropDownList") %>',
data: JSON.stringify({ serviceTypeID: TryParseInt(hiddenserviceTypeID.value, 0), clientContractID: TryParseInt(clientContractID, 0), serviceDate: serviceDate, tableName: tableName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
a(data);
}
,error: function () {
alert('HydrateFacilityDropDownList error');
}
, complete: function () {
}
});
}
function a(data) {
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
var tableName = "resultTable";
if (facilityDropDownList.value != "") {
selectedFacilityID = facilityDropDownList.value;
}
$(facilityDropDownList).empty();
$(facilityDropDownList).prepend($('<option />', { value: "", text: "", selected: "selected" }));
$(data.d).find(tableName).each(function () {
var OptionValue = $(this).find('OptionValue').text();
var OptionText = $(this).find('OptionText').text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
$(facilityDropDownList).append(option);
});
if ($(facilityDropDownList)[0].options.length > 1) {
if ($(facilityDropDownList)[0].options[1].text == "In Home") {
$(facilityDropDownList)[0].selectedIndex = 1;
}
}
if (TryParseInt(selectedFacilityID, 0) > 0) {
$(facilityDropDownList)[0].value = selectedFacilityID;
}
facilityDropDownList_OnChange();
}
Code Behind
[WebMethod]
public static string HydrateFacilityDropDownList(int serviceTypeID, int clientContractID, DateTime serviceDate, string tableName)
{
List<PackageAndServiceItemContent> svcItems = ServiceItemContents;
List<Facility> facilities = Facility.GetAllFacilities().ToList();
if (svcItems != null)
{
// Filter results
if (svcItems.Any(si => si.RequireFacilitySelection))
{
facilities = facilities.Where(f => f.FacilityTypeID > 0).ToList();
}
else
{
facilities = facilities.Where(f => f.FacilityTypeID == 0).ToList();
}
if (serviceTypeID == 0)
{
facilities.Clear();
}
}
return ConvertToXMLForDropDownList(tableName, facilities);
}
public static string ConvertToXMLForDropDownList<T>(string tableName, T genList)
{
// Create dummy table
DataTable dt = new DataTable(tableName);
dt.Columns.Add("OptionValue");
dt.Columns.Add("OptionText");
// Hydrate dummy table with filtered results
if (genList is List<Facility>)
{
foreach (Facility facility in genList as List<Facility>)
{
dt.Rows.Add(Convert.ToString(facility.ID), facility.FacilityName);
}
}
if (genList is List<EmployeeIDAndName>)
{
foreach (EmployeeIDAndName employeeIdAndName in genList as List<EmployeeIDAndName>)
{
dt.Rows.Add(Convert.ToString(employeeIdAndName.EmployeeID), employeeIdAndName.EmployeeName);
}
}
// Convert results to string to be parsed in jquery
string result;
using (StringWriter sw = new StringWriter())
{
dt.WriteXml(sw);
result = sw.ToString();
}
return result;
}
$get return XHR object not the return value of the success call and $get function isn't synchronous so you should wait for success and check data returned from the call
these two lines do something different than what you expect
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
change to something similar to this
var facilityDropDownList;
$.ajax({
url: '<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>',
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
facilityDropDownList= data;
}
});

My object is undefined when I test it i QUnit

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

Categories

Resources