Intermitient "Cannot reinitialise DataTable" error - javascript

I am making a project with a DataTable (https://datatables.net) and the issue I am having is pretty strange.
Sometimes when I load the page, everything works 100% and other times when I load the page I get this error from DataTables in a popup:
DataTables warning: table id=resdatatable - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
As I have said, there's no sure fire way to trigger this. If I hit refresh sometimes it will work, sometimes it will give me that error.
I am not trying to reinitialize the DataTable, so I am a bit confused on why this is happening. I checked the link in the description but I am not understanding how to remedy this.
Here is my code:
let statusList = getStatusList();
function getRes(callback) { // ADDED CALLBACK
let city = document.getElementById("cityselect").value;
$.ajax({
type: 'get',
url: 'getreservationstable.php?city='+city,
dataType: 'json',
cache: false,
success: callback // USED CALLBACK
});
}
function changeCity()
{
$('#resdatatable').DataTable().ajax.reload();
}
getRes(function (result) { // APPLIED CALLBACK
$('#resdatatable').DataTable({
data: result, // YOUR RESULT
columns: [
{ data: 'id', title: 'ID' },
{ data: 'bookingdatetime', title: 'Booking Date' },
{ data: 'name', title: 'Name' },
{ data: 'class', title: 'Class' },
{ data: 'pickupdatetime', title: 'Pick up' },
{ data: 'duration', title: 'Duration' },
{ data: 'dropdatetime', title: 'Drop off' },
{ data: 'age', title: 'Age' },
{ data: 'coverage', title: 'Coverage' },
{ data: 'quote', title: 'Quote' },
{
data: 'status',
title: 'Status',
render: function(data, type, row) {
let isKnown = statusList.filter(function(k) { return k.id === data; }).length > 0;
if (isKnown) {
return $('<select id ="resstatus' + row.id + '" onchange="changeResStatus(' + row.id + ')">', {
id: 'resstatus-' + row.id, // custom id
value: data
}).append(statusList.map(function(knownStatus) {
let $option = $('<option>', {
text: knownStatus.text,
value: knownStatus.id
});
if (row.status === knownStatus.id) {
$option.attr('selected', 'selected');
}
return $option;
})).on('change', function() {
changeresstatus(row.id); // Call change with row ID
}).prop('outerHTML');
} else {
return data;
}
}
}
]
});
});
/**
* jQuery plugin to convert text in a cell to a dropdown
*/
(function($) {
$.fn.createDropDown = function(items) {
let oldTxt = this.text();
let isKnown = items.filter(function(k) { return k.id === oldTxt; }).length > 0;
if (isKnown) {
this.empty().append($('<select>').append(items.map(function(item) {
let $option = $('<option>', {
text: item.text,
value: item.id
});
if (item.id === oldTxt) {
$option.attr('selected', 'selected');
}
return $option;
})));
}
return this;
};
})(jQuery);
// If you remove the renderer above and change this to true,
// you can call this, but it will run once...
if (false) {
$('#resdatatable > tbody tr').each(function(i, tr) {
$(tr).find('td').last().createDropDown(statusList);
});
}
function getStatusList() {
return [{
id: 'Confirmed',
text: 'Confirmed'
}, {
id: 'Unconfirmed',
text: 'Unconfirmed'
}, {
id: 'Open',
text: 'Open'
}, {
id: 'Closed',
text: 'Closed'
}, {
id: 'Canceled',
text: 'Canceled'
}];
}
function changeResStatus(str1) {
var id = str1;
var status = document.getElementById("resstatus" + id).value;
var mailres = "";
var r = confirm("Change Status for ID # " + id + " to " + status + "?");
if (r == true) {
if (document.getElementById("resstatus" + id).value == "Confirmed"){
var s = confirm("Send ID # " + id + " a confirmation email?");
if (s == true) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").setAttribute ("data-notify-msg", this.responseText);
document.getElementById("result").setAttribute ("data-notify-type", "info");
SEMICOLON.widget.notifications(document.getElementById("result"));
}
};
xmlhttp.open("GET","sendconfirmationemail.php?id="+id,true);
xmlhttp.send();
}
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").setAttribute ("data-notify-msg", this.responseText);
document.getElementById("result").setAttribute ("data-notify-type", "info");
SEMICOLON.widget.notifications(document.getElementById("result"));
}
};
xmlhttp.open("GET","changeresstatus.php?id="+id+"&status="+status,true);
xmlhttp.send();
}else{
document.getElementById("result").setAttribute ("data-notify-msg", "Change status action aborted");
document.getElementById("result").setAttribute ("data-notify-type", "error");
SEMICOLON.widget.notifications(document.getElementById("result"));
}
}
$(document).ready(function() {
var table = $('#resdatatable').DataTable();
$('#resdatatable tbody').on('click', 'tr', function () {
var data = table.row( this ).data().id;
$.ajax({
type: 'POST',
url: 'getreservationsdetails.php',
dataType: 'json',
data: { id:data, },
success: function(response) {
$('#resulttitle').html("Booking ID # " + response[0].id);
$('#resdetname').html(response[0].name);
$('#resdetbdate').html(response[0].bookingdatetime);
$('#resdetadd').html("<br>" + response[0].address + "<br>" + response[0].city + "<br>" + response[0].state + " " + response[0].post);
$('#resdetphone').html(response[0].phone);
$('#resdetemail').html(response[0].email);
$('#resdetdln').html(response[0].dlnum);
$('#resdetdle').html(response[0].dlexp);
$('#resdetdlc').html(response[0].dlcountry);
$('#resdetpickup').html(response[0].pickuploc + " " + response[0].pickupdatetime);
$('#resdetduration').html(response[0].duration);
$('#resdetdrop').html(response[0].droploc + " " + response[0].dropdatetime);
$('#resdetclass').html(response[0].class);
$('#resdetcoverage').html(response[0].coverage);
$('#resdetage').html(response[0].age);
$('#resdetnumofdrivers').html(response[0].numofdrivers);
$('#resdetroadside').html(response[0].roadsideass);
$('#resdetafterhoursdrop').html(response[0].afterhoursdrop);
$('#resdetpromo').html(response[0].promo);
$('#resdetquote').html(response[0].quote);
$('#resdetaddcomments').html(response[0].name);
$('#resdetip').html(response[0].ip);
$("#modalresult").modal();
}
});
} );
} );
Edit:
Upon further examination, this error seems to be caused by the line var table = $('#resdatatable').DataTable(); in $(document).ready(function() { - if I remove that line, everything works just fine. How do I make this work???

Your error come from the fact you try to access a Database object which has not been initialized yet by getRes().
Because on $(document).ready you were creating a first database with no options, when getRes got trigger you should update its content instead of creating a second Database() on top of the same element (which explain the "Cannot reinitialise DataTable")
Try to move the table var from your document ready to your on event:
$(document).ready(function() {
$('#resdatatable tbody').on('click', 'tr', function () {
var table = $('#resdatatable').DataTable();
var data = table.row( this ).data().id;
Or maybe init the $('#resdatatable tbody').on on getRes() as it might not have access to tbody yet:
getRes(function (result) { // APPLIED CALLBACK
$('#resdatatable').DataTable({
...
});
$('#resdatatable tbody').on('click', 'tr', function () {
...

How I fixed this problem:
I added a 1ms delay for the code to run:
setTimeout(function() {
$(document).ready(function() {
var table = $('#resdatatable').DataTable();
$('#resdatatable tbody').on('click', 'tr', function () {
var data = table.row( this ).data().id;
$.ajax({
type: 'POST',
url: 'getreservationsdetails.php',
dataType: 'json',
data: { id:data, },
success: function(response) {
$('#resulttitle').html("Booking ID # " + response[0].id);
$('#resdetname').html(response[0].name);
$('#resdetbdate').html(response[0].bookingdatetime);
$('#resdetadd').html("<br>" + response[0].address + "<br>" + response[0].city + "<br>" + response[0].state + " " + response[0].post);
$('#resdetphone').html(response[0].phone);
$('#resdetemail').html(response[0].email);
$('#resdetdln').html(response[0].dlnum);
$('#resdetdle').html(response[0].dlexp);
$('#resdetdlc').html(response[0].dlcountry);
$('#resdetpickup').html(response[0].pickuploc + " " + response[0].pickupdatetime);
$('#resdetduration').html(response[0].duration);
$('#resdetdrop').html(response[0].droploc + " " + response[0].dropdatetime);
$('#resdetclass').html(response[0].class);
$('#resdetcoverage').html(response[0].coverage);
$('#resdetage').html(response[0].age);
$('#resdetnumofdrivers').html(response[0].numofdrivers);
$('#resdetroadside').html(response[0].roadsideass);
$('#resdetafterhoursdrop').html(response[0].afterhoursdrop);
$('#resdetpromo').html(response[0].promo);
$('#resdetquote').html(response[0].quote);
$('#resdetaddcomments').html(response[0].name);
$('#resdetip').html(response[0].ip);
$("#modalresult").modal();
}
});

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

Bootstrap Select2 doesn't firing select event on paste until type any word

I use bootstrap select2 v4.* on my site (Yii 2.x) and have met a problem:
The event select2:select doesn't firing on text paste with ctrl+v until I type any text. After typing - it works fine. What i'm doing wrong?
JS:
function formatResult(data) {
var content = '<span>' + data.id + '\t' + data.text + '</span>';
return $(content);
};
function formatSelection(data) {
var content = '<span>' + data.id + '</span>';
return $(content);
}
$('#wiz-asin-search').select2({
tags: true,
minimumInputLength: 3,
placeholder: 'specify asin..',
ajax: {
url: '/keyword-tracker/get-mwslisting-asins',
method: 'GET',
dataType: 'json',
data: function (params) {
return {
searchAsin: params.term
}
},
results: function (data) {
return { results: data.results };
}
},
templateResult: formatResult,
templateSelection: formatSelection,
escapeMarkup: function(m) { return m; }
}).on('select2:select', function(){
var asin = $(this).val();
console.log('asinSearch.change fired: ' + asin);
validationHighLight(false);
validateAsin(asin);
});
The solution is:
initialize select2 with some data.
$('#wiz-asin-search').select2({
// allowClear: true,
tags: true,
minimumInputLength: 3,
data: [
{
id: ' ',
text: 'testAsin'
}
],
...
and it will work fine.
You simply use this code:
$('#yourElement').select2();
Had a similar issue and resolved it using the createTag callback.
$('select').select2({
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
if (this.$element.find('option').length === 0) {
this.$element.append($('<option data-select2-tag="true">'));
}
return {
id: term,
text: term
}
}
});

Handsontable autosave - ajax not defined

I copied the code from Handsontable official documentation, into a JSFiddle. This is handsontable 0.34.5.
I am getting an error in chrome console:
"ajax is not defined".
Code as follows, pre-loaded with handsontable.full.min.js and handsontable.full.min.css
HTML:
<div class="ajax-container">
<div class="controls">
<button name="load" id="load" class="intext-btn">Load</button>
<button name="save" id="save" class="intext-btn">Save</button>
<label>
<input type="checkbox" name="autosave" id="autosave" checked="checked" autocomplete="off">Autosave</label>
</div>
<pre id="example1console" class="console">Click "Load" to load data from server</pre>
<div id="example1" class="hot handsontable"></div>
</div>
Script:
var
$$ = function(id) {
return document.getElementById(id);
},
container = $$('example1'),
exampleConsole = $$('example1console'),
autosave = $$('autosave'),
load = $$('load'),
save = $$('save'),
autosaveNotification,
hot;
hot = new Handsontable(container, {
startRows: 8,
startCols: 6,
rowHeaders: true,
colHeaders: true,
afterChange: function(change, source) {
if (source === 'loadData') {
return; //don't save this change
}
if (!autosave.checked) {
return;
}
clearTimeout(autosaveNotification);
ajax('scripts/json/save.json', 'GET', JSON.stringify({
data: change
}), function(data) {
exampleConsole.innerText = 'Autosaved (' + change.length + ' ' + 'cell' + (change.length > 1 ? 's' : '') + ')';
autosaveNotification = setTimeout(function() {
exampleConsole.innerText = 'Changes will be autosaved';
}, 1000);
});
}
});
Handsontable.dom.addEvent(load, 'click', function() {
ajax('scripts/json/load.json', 'GET', '', function(res) {
var data = JSON.parse(res.response);
hot.loadData(data.data);
exampleConsole.innerText = 'Data loaded';
});
});
Handsontable.dom.addEvent(save, 'click', function() {
// save all cell's data
ajax('scripts/json/save.json', 'GET', JSON.stringify({
data: hot.getData()
}), function(res) {
var response = JSON.parse(res.response);
if (response.result === 'ok') {
exampleConsole.innerText = 'Data saved';
} else {
exampleConsole.innerText = 'Save error';
}
});
});
Handsontable.dom.addEvent(autosave, 'click', function() {
if (autosave.checked) {
exampleConsole.innerText = 'Changes will be autosaved';
} else {
exampleConsole.innerText = 'Changes will not be autosaved';
}
});
The code of the ajax function they are using is rather simple, is just a wrapper around XMLHttpRequest.
NOTE: I got it by just executing ajax.toString() via devtools on their docs page. It isn't referencing external functions, so it will work as is.
function ajax(url, method, params, callback) {
var obj;
try {
obj = new XMLHttpRequest();
} catch (e) {
try {
obj = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
obj = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support Ajax.");
return false;
}
}
}
obj.onreadystatechange = function () {
if (obj.readyState == 4) {
callback(obj);
}
};
obj.open(method, url, true);
obj.setRequestHeader("X-Requested-With", "XMLHttpRequest");
obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
obj.send(params);
return obj;
}

jQuery autocomplete with multiple items not working

I am working on jQuery autocomplete which as two items in a <ul>.
I am getting json item from $.getJSON function and the json object looks like :
[{
"merchant_name": "Myntra",
"merchant_details": "Flat Rs.225 Cashback"
}, {
"merchant_name": "Adlabs imagica",
"merchant_details": "Rs 170 per sale"
}, {
"merchant_name": "godaam",
"merchant_details": "Rs 140 per sale"
}, {
"merchant_name": "Homeshop18",
"merchant_details": "Upto 8% Cashback"
}]
My function looks as follows:
$('#search_bar').keyup(function(e) {
var searched = $('#search_bar').val()
$.getJSON('<?php echo base_url();?>get_data', 'title=' + searched, function(result) {
var elements = [];
$.each(result, function(i, val) {
elements.push({
'merchant_name': val.merchant_name,
'merchant_details': val.merchant_details
})
}) $('#search_bar').autocomplete({
delay: 0,
source: elements,
select: function(event, ui) {
$("input#search_bar").val(ui.item.merchant_name + " / " + ui.item.merchant_details);
$("#get").click();
}.data("autocomplete")._renderItem = function(ul, item) {
return $("<li></li>").data("item.autocomplete", item).append("<a><strong>" + item.merchant_name + "</strong> / " + item.merchant_details + "</a>").appendTo(ul);
};
})
})
});
I am not able to proceed forward.
Please help me to solve this one.
I wrote this for one of my projects and it works perfectly. I'm not sure why you are detecting keyup when autocomplete does that for you... But this snippet should give you all the functionality you need.
$("#edit_profile .location").autocomplete({
source: function(request, response) {
$.ajax({
url: BASE_URL + "lib/ajax.php",
type: "GET",
data: "autocomplete_location=1&term=" + request.term,
cache: false,
success: function(resp) {
try {
json = $.parseJSON(resp);
} catch (error) {
json = null;
}
//
if (json && json.status == "OK") {
//
response($.map(json.predictions, function(item) {
return {
label: item.description,
value: item.description
}
}));
//
}
}
});
},
minLength: 1,
change: function (event, ui) {
if (!ui.item){
$(this).val("");
}
}
});

Reactive http requests in JavaScript

Sorry for my English. I made some test client for test our web server, but I am unhappy with my work. Please help me improve my code.
I want to make serial HTTP requests. I have Array with test requests:
Aua.Queries = ko.observableArray([
new Query("/srv?key=value&key2=someValue", 300, "comment for this request"),
new Query("/srv?someKey=SomeValue", 0, "comment for this request")
]);
(in Aua.Queries array 24 queries)
My wrapper for Aua.Queries observableArray:
function Query(query, result, comment) {
var me = this;
me.Query = "http://mydomain.com?" + query;
me.Result = result;
me.Comment = comment;
me.Selected = ko.observable(false);
}
When click send handler, I do this:
Aua.SendHandler = function () {
Aua.Loading(true);
Aua.Responses([]);
if (Aua.Advanced() == true) {
var queries = Aua.Queries();
console.log("Selected Request Count: ",
Enumerable.From(queries).Where("$.Selected() == true").Select(function(query) {
console.log("Result: ", query.Result);
Aua.Url(query.Query);
query.Selected(false);
sendRequest();
}).Count());
}
else if (Aua.RequestCount() > 1) {
for (var i = Aua.RequestCount(); i > 0; i--) {
Aua.RequestCount(i);
setUrlByStatus();
sendRequest();
}
}
else
sendRequest();
};
And sendRequest Handler:
function sendRequest() {
console.log("Sending request to: ", Aua.Url());
$.ajax(Aua.Url(), {
dataType: 'text',
cache: false,
type: 'GET',
success: function(data, status, xhr) {
Aua.Responses.push({
"Data": data,
"Status": xhr.status + " " + xhr.statusText
});
prettyPrint();
},
error: function(xhr, status, data) {
Aua.Responses.push({
"Data": data,
"Status": xhr.status + " " + xhr.statusText
});
prettyPrint();
console.log("Error: ", Aua.Responses());
},
complete: function() {
Aua.Loading(false);
}
});
}
Set type of request format.
function setUrlByStatus() {
if (Aua.RequestStatus() === "error")
Aua.Url(Aua.Queries()[Math.floor(Math.random() * Aua.Queries().length)].Query);
else
Aua.Url(
"http://mydomain.com?" +
"action=" + Aua.Action() +
"&number=" + Aua.Number());
}
A have 3 types of sending request.
Send multiple request from Aua.Queries array.
Send requests by depent in count.
And Send 1 request in input.
I do my self.
And i learned how organaize my code
/*
Client requests for tes our server
Make different demands on the Serer.
Query setings:
     Send something that is in the input.
     Send to a specified number of times queries and allow the user to choose what kind of answer he wants, success or error.
         For successful actions are random data request: email, account, paper.
     Send requests from the table.
     All the answers to print. Prettify XML response.
     After the data to make a progress report
         The following table show: Status Code, Comments, Quantity.
     HTTP status display for each response received and paint the fatal errors in red.
*/
(function (global, undefined) {
function ajaxObject(url, query, response, loading) {
console.log("Query: ", query());
var catched = query();
return $.ajax({
cache: false,
dataType: "text",
type: "GET",
url: url() + catched,
success: function (data, status, xhr) {
response.push({
Data: data,
Query: catched,
Status: xhr.status + ' ' + xhr.statusText
});
},
error: function (xhr, status, data) {
response.push({
Data: data,
Query: catched,
Status: xhr.status + " " + xhr.statusText
});
},
complete: function () {
loading(false);
prettyPrint();
}
});
}
function Query(query, result, comment) {
var me = this;
me.Query = query;
me.Result = result;
me.Comment = comment;
me.Selected = ko.observable(false);
me.Describtion = ko.observable(comment);
me.DescribtionComment = function (data) { me.Describtion(data.Comment); };
me.DescribtionQuery = function (data) { me.Describtion(data.Query); };
}
var queries = [
new Query("/zibaba?paper=go&id=1&account=someacc&date=20130221174323", 453, "Error. Expected parameter test"),
new Query("/zibaba?paper=go&account=someacc", 0, "Expected parameter test"),
new Query("/zibaba?paper=do&id=3&account=someacc&date=20130221174323", 1, " Forbidden"))
];
var Aua = global.Aua = new function Aua() { };
Aua.Configuration = {
Advanced: {
Queries: queries,
QueriesSelectAll: ko.observable(false),
Toggle: ko.observable(false)
},
Counter: ko.observable(1),
Query: ko.observable(),
Url: ko.observable(),
Status: ko.observable("success")
};
Aua.Configuration.Advanced.QueriesSelectAll.subscribe(function () {
var qs = Aua.Configuration.Advanced.Queries;
for (var i = 0; i < qs.length; i++)
qs[i].Selected(!qs[i].Selected());
});
Aua.IsLoading = ko.observable(false);
Aua.SendHandler = function() {
Aua.IsLoading(true);
Aua.Responses([]);
if (Aua.Configuration.Advanced.Toggle() === true) {
$.when(Enumerable.From(Aua.Configuration.Advanced.Queries)
.Where("$.Selected() === true")
.Select(function(current) {
Aua.Configuration.Query(current.Query);
return ajaxObject(Aua.Configuration.Url, Aua.Configuration.Query, Aua.Responses, Aua.IsLoading);
}).ToArray());
} else {
$.when(Enumerable.Generate(function() {
var papers;
if (Aua.Configuration.Status() == "success") {
papers = ["do", "go"];
Aua.Configuration.Query(
"?account=" + Math.floor(Math.random() * 1234567 + 1) +
("&paper=" + papers[Math.floor(Math.random() * papers.length)]) +
("&id=" + Math.floor(Math.random() * 123754 + 1)));
} else if (Aua.Configuration.Status() == "error") {
papers = ["do", "go", "justdoit"];
var accounts = [Math.floor(Math.random() * 1234567 + 1), " ", Math.floor(Math.random() * 4532 + 1)],
ids = [" ", (Math.floor(Math.random() * 123754 + 1)), (Math.floor(Math.random()))];
Aua.Configuration.Query(
"?account=" + accounts[Math.floor(Math.random() * accounts.length)] +
"&paper=" + (papers[Math.floor(Math.random() * papers.length)]) +
"&id=" + (ids[Math.floor(Math.random() * ids.length)]));
}
return ajaxObject(Aua.Configuration.Url, Aua.Configuration.Query, Aua.Responses, Aua.IsLoading);
}, Aua.Configuration.Counter()).ToArray());
}
};
Aua.ResetHandler = function () { location.reload(); };
Aua.Statistics = {
Code: ko.observable(0),
Comment: ko.observable(0),
Quantity: ko.observable(0)
};
Aua.Responses = ko.observableArray([{
Data: ko.observable(),
Status: ko.observable(-1)
}]);
Aua.Responses([]);
$(document).on("ready", function () {
ko.applyBindings(Aua);
});
})(window);
Sorry for my English

Categories

Resources