IE 11 changing URL - url

I am getting strange behaviour in IE 11.
When I go to my web application using URL
"hostname:port/myapp-web/app/login.jsp"
The login page is displayed, And Login is done successfully.
Now. Problem is that, after logging in, App's landing page is index.html.
So URL should be "hostname:port/myapp-web/app/index.html"
Instead, IE changes it to "hostname:port///index.html"
Now, when I try to do any other operation or navigation, it fails because base URL is changed and my JS code cannot find app context root and all AJAX calls fails.
I tried searching over internet for the same, but couldn;t find any answer.
Please help if anyone has idea about such behaviour.
P.S. App is working fine in IE: 8/9, Chrome and FF.
I found something related to UTF-* character URLs but my app uses plain text URL with NO special characters.
App is developed using Spring for server side and KnockoutJS, HTML for UI.
Thanks in advance for the help.
index.html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=EDGE" />
<!-- script includes -->
</head>
<body>
<!-- NavigationBar -->
</body>
<script type="text/javascript">
app.initialize(); // app.js
$.getJSON('/myapp-web/Security/authorise', function (response) {
app.common.navbar.reRenderNavBar(response);
app.navigation = new Navigation("AdminHome"); // navigation.js
// This navigation causes IE11 to change URL to http://host:port///#AdminHome
// it should be // http://host:port/myapp-web/app/index.html#AdminHome
});
</script>
</html>
Navigation.js
var ua = window.navigator.userAgent
var msie = ua.indexOf("MSIE ")
var ieVer = -1;
if (msie > 0) {
var ieVer = ua.substring(msie + 5, ua.indexOf(".", msie));
//console.log(ieVer);
}
var NavigationInput = function (pName, pValue) {
this.paramName = pName;
this.paramValue = pValue;
this.toString = function () {
return pName + ":" + pValue;
}
}
var Navigation = function (startupView) {
var self = this;
this.navInput = [];
this.navViewModel = null;
this.navViewModelInitComplete = false;
// this.navigate = function navigate(view) {
//
// if (view !== this.currentView) {
// self.loadView(view, true, null);
// }
// }
this.navigateWithParams = function navigateWithParams(view, params) {
self.loadView(view, true, params);
}
this.goBack = function goBack() {
history.go(-1);
//history.back();
}
this.loadView = function (view, pushHistory, params) {
var contentframe = $("#content");
//app.consolePrintInfo("navigation", "previous view: " + self.currentView + " new view: " + view);
if (typeof (self.currentView) != 'undefined' && self.currentView
&& self.currentView.toLowerCase() == view.toLowerCase()
&& isParamsEqual(params)) {
return;
}
var constructedView;
constructedView = "Views/" + view + "/" + view + ".html"
contentframe.load(constructedView, function () {
self.currentView = view;
modUrl = view;
if (params != null) {
if (params instanceof String) {
modUrl = params;
}
else {
var queryStr = self.convertParamsToQueryString(params);
modUrl += "?" + queryStr;
}
// if (typeof(app.navigation.navViewModel) != 'undefined'
// && app.navigation.navViewModel
// && !app.navigation.navViewModelInitComplete)
// {
// app.navigation.navViewModelInitComplete = app.navigation.navViewModel.initViewModel(self.convertQueryStringToParams(modUrl));
// }
}
if (pushHistory) {
if (ieVer > 6) {
window.history.pushState(view, null, modUrl);
}
else {
window.history.pushState(view, null, "#" + modUrl);
}
}
app.consolePrintInfo("navigation", "modified url:" + modUrl + " view model: " + app.navigation.navViewModel);
var navInputs = self.convertQueryStringToParams(modUrl);
self.urlInputs = navInputs;
app.navigation.navViewModelInitComplete = app.navigation.navViewModel.initViewModel(navInputs);
//$.getScript("Views/" + view + ".js", function () {
//});
});
isParamsEqual = function (iParams) {
if ((typeof(self.urlInputs) == 'undefined' || !self.urlInputs)
&& (typeof(iParams) == 'undefined' || !iParams)) {
return true;
}
else if (app.utility.isObjectNull(self.urlInputs) && app.utility.isObjectNull(iParams)) {
return true;
}
else {
return false;
}
}
}
this.convertParamsToQueryString = function (params) {
var result = "";
for (var i = 0; i < params.length; i++) {
if (i > 0) {
result += "&";
}
result += params[i].paramName + "=" +
params[i].paramValue;
}
return result;
};
this.convertQueryStringToParams = function (modUrl) {
var inputs = null;
var fragments = modUrl.split("?");
if (fragments && fragments.length == 2) {
var f = fragments[1].split("&");
if (f && f.length > 0) {
for (var i = 0; i < f.length; i++) {
var inp = f[i].split("=");
if (inputs == null) inputs = [];
inputs.push(new NavigationInput(inp[0], inp[1]));
}
}
}
return inputs;
};
this.back = function () {
if (history.state) {
var view = self.getView();
self.loadView(view, false, self.convertQueryStringToParams(location.href));
} else {
var view = self.getView();
self.loadView(view, true, self.convertQueryStringToParams(location.href));
}
};
this.getView = function () {
var fragments = location.href.split('#');
if (fragments && fragments.length === 2) {
var inFrag = fragments[1].split('?');
if (inFrag && inFrag.length === 2) {
return inFrag[0];
}
else {
return fragments[1];
}
} else {
return startupView;
}
};
this.loadView(this.getView(), true, this.convertQueryStringToParams(location.href));
$(window).on('popstate', self.back);
}
app.js:
-----------------
app = {};
// utilities
app.utility = {};
app.ui = {};
// common
app.common = {};
// validation
app.validation = {};
// common components
app.common.navbar = {};
app.common.authorisation = {};
app.initialize = function () {
$.blockUI.defaults.message = '<h4><img src="images/busy.gif" /> Processing...</h4>';
$.blockUI.defaults.css.border = '2px solid #e3e3e3';
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
//$(document).click(function() { $(".popover").remove(); });
}
app.consolePrintInfo = function (tag, message) {
if (typeof(console) != 'undefined' && console)
console.info(tag + ": " + message);
}
app.ui.showAppError = function (message) {
app.consolePrintInfo("App", "displaying error message: " + message);
$('#error-console').removeClass('app-error-console-hidden');
$('#error-console').removeClass('alert-info');
$('#error-console').addClass('alert-error');
$('#error-console').html(message);
}
app.ui.showAppInfo = function (message) {
app.consolePrintInfo("App", "displaying info message: " + message);
$('#error-console').show();
$('#error-console').removeClass('app-error-console-hidden');
$('#error-console').removeClass('alert-error');
$('#error-console').addClass('alert-info');
$('#error-console').html(message);
$('#error-console').fadeOut(4000);
}
app.utility.addQueryParameter = function (url, paramName, paramValue) {
var rUrl = url;
if (typeof(paramName) != 'undefined' && paramName
&& typeof(paramValue) != 'undefined' && paramValue) {
if (rUrl.indexOf("?") != -1) {
rUrl = rUrl + "&" + paramName + "=" + paramValue;
}
else {
rUrl = rUrl + "?" + paramName + "=" + paramValue;
}
}
return rUrl;
}
app.utility.addSearchParameter = function (paramName, paramValue) {
var rValue = undefined;
if (typeof(paramName) != 'undefined' && paramName
&& typeof(paramValue) != 'undefined' && paramValue) {
rValue = paramName + ":" + paramValue;
}
return rValue;
}
app.utility.searchParameter = function (inputKeyArray, paramName) {
if (inputKeyArray instanceof Array) {
for (var i = 0; i < inputKeyArray.length; i++) {
if (inputKeyArray[i].paramName == paramName) {
return inputKeyArray[i].paramValue;
}
}
}
return undefined;
}
app.utility.isObjectNull = function (obj) {
return typeof(obj) == 'undefined' || obj == undefined || !obj;
}
app.utility.isObjectNotNull = function (obj) {
return typeof(obj) != 'undefined' && obj;
}
app.utility.isFunction = function (obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
};
app.utility.parseError = function (em) {
if (!app.utility.isObjectNull(em)) {
jem = JSON.parse(em);
var keyArray = new Array();
keyArray.push(jem.errorCode);
keyArray.push(jem.errorMessage);
return keyArray;
}
else {
return undefined;
}
}
app.utility.showAppErrorDialog = function (errTitle, errMessage) {
if (!app.utility.isObjectNull(errMessage)) {
var $message = $("Error:" + errMessage)
.dialog({autoOpen: false, width: 300, title: errTitle, modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
}
}}
);
$message.dialog('open');
}
}
app.utility.showErrorDialog = function (err) {
if (!app.utility.isObjectNull(err)) {
var $message = $('<div><p>Unfortunately, there has been error in the server!</p><p>' + err[1] + '</p><p>Please send the screenshot to developer team</div>')
.dialog({autoOpen: false, width: 300, title: err[0], modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
}
}}
);
$message.dialog('open');
}
}
app.utility.showDialog = function (heading, text) {
if (!app.utility.isObjectNull(heading) && !app.utility.isObjectNull(text)) {
var $message = $('<div><p>' + text + '</p></div>')
.dialog({autoOpen: false, width: 300, title: heading, modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
}
}}
);
$message.dialog('open');
}
}
app.utility.populateToolTip = function () {
$("img[id^='tooltip']").each(function () {
var idName = $(this).attr("id");
$('#' + idName).tooltip('toggle');
$('#' + idName).tooltip('hide');
});
};
app.utility.isNotEmptyNumberValue = function (input) {
if (app.utility.isObjectNull(input)) {
return true;
}
if (!isNaN(input) && isFinite(input) && ("" + input).indexOf("-") == -1 && ("" + input).indexOf("e") == -1) {
return true;
}
return false;
};
app.utility.isNotEmptyWholeNumberValue = function (input) {
if (app.utility.isObjectNull(input)) {
return true;
}
if (!isNaN(input) && isFinite(input) &&
("" + input).indexOf("-") == -1 && ("" + input).indexOf(".") == -1 && ("" + input).indexOf("e") == -1) {
return true;
}
return false;
};
app.utility.isNumberValue = function (input) {
if (!isNaN(input) && isFinite(input)) {
return true;
}
return false;
};
app.utility.doHttpRequest = function (input) {
if (app.utility.isObjectNull(input) || app.utility.isObjectNull(input.rURL)) {
app.utility.showDialog("Error!", "Unable to find required inputs. Error in sending request");
return false;
}
app.consolePrintInfo("HTTP REQUEST: ", "[URL] :" + input.rURL);
app.consolePrintInfo("HTTP REQUEST: ", "[Type] :" + input.rType);
app.consolePrintInfo("HTTP REQUEST: ", "[Input] :" + input.rDataToSend);
$.ajax({
url: input.rURL,
type: input.rType,
contentType: 'application/json',
cache: false,
data: input.rDataToSend,
dataType: 'json'
}).success(function (response) {
app.consolePrintInfo("HTTP REQUEST: ", "[Output - success] :" + JSON.stringify(response));
if (!app.utility.isObjectNull(input.rOnSuccessFunction)) {
input.rOnSuccessFunction(response);
}
else if (!app.utility.isObjectNull(input.rOnSuccessMessage)) {
app.utility.showDialog("Complete", input.rOnSuccessMessage);
}
}).error(function (response) {
if (response.status == 401) {
// session expired. redirect to login page.
app.consolePrintInfo("HTTP REQUEST: ", "[Output - failure] : Session Expired");
var $message = $('<div><p>' + response.responseText + '</p></div>')
.dialog({autoOpen: false, width: 300, title: 'Session Expired', modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
// Remove the cached data
//comp_storage.remove("lastStoredValue");
//comp_storage.remove("permissionStr");
//window.open("/aid-web/logout", "_self");
app.utility.doLogout();
}
}}
);
$message.dialog('open');
}
else if (response.status == 400) {
app.consolePrintInfo("HTTP REQUEST: ", "[Output - failure] : Server Error");
var $message = $('<div><p>' + response.responseText + '</p></div>')
.dialog({autoOpen: false, width: 300, title: 'Server Error', modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
}
}}
);
$message.dialog('open');
}
else {
app.consolePrintInfo("HTTP REQUEST: ", "[Output - failure] :" + response.responseText);
if (!app.utility.isObjectNull(input.rOnErrorFunction)) {
input.rOnErrorFunction(response.responseText);
}
else if (!app.utility.isObjectNull(input.rOnErrorMessage)) {
app.utility.showDialog("Error", input.rOnErrorMessage);
}
}
});
};
app.utility.doLogout = function () {
comp_storage.remove("lastStoredValue");
comp_storage.remove("permissionStr");
window.open("/aid-web/logout", "_self");
};
// common
// Nav bar component
app.common.navbar.reRenderNavBar = function (content) {
// [SAMPLE] To update the common component. create a view model of that
// component. set the needed variables.
// and *definately call applyBindings()*
app.common.navbar.navBarViewModel = new ko.navBarComponent.viewModel({
// set compt. values if needed. like below.
//navBarComponent_isEmpty:ko.observable(false)
});
app.common.navbar.navBarViewModel.navBarComponent_reRender(content);
ko.applyBindings(app.common.navbar.navBarViewModel, $('#nav-bar').get(0));
}
// Authorisation component
app.common.authorisation.storeRoleInfo = function (permissionArr) {
comp_auth.storeRoleInfo(permissionArr);
};
app.common.authorisation.isRolePresent = function (roleName) {
return comp_auth.isRolePresent(roleName);
};
// validation
app.validation.highlightElement = function (id, text) {
}
app.validation.highlightError = function (eleId, heading, text) {
if (!app.utility.isObjectNull(heading) && !app.utility.isObjectNull(text) && !app.utility.isObjectNull(eleId)) {
$("#" + eleId).addClass("ui-state-error");
var $message = $('<div><p>' + text + '</p></div>')
.dialog({
autoOpen: true,
width: 300,
title: heading, modal: true,
close: function () {
setTimeout(function () {
jQuery("#" + eleId).removeClass("ui-state-error");
}, 500);
},
buttons: {
Ok: function () {
$(this).dialog("close");
setTimeout(function () {
jQuery("#" + eleId).removeClass("ui-state-error");
}, 500);
}
},
overlay: {
opacity: 0.1,
},
}
).parent().addClass("ui-state-error");
}
}

Related

Camera doesn't work after compilation

I use Ionic Framework.
Camera works perfectly in Ionic View. But it doesn't work after compilitaion on iOS.
Please, help to find out what is the problem.
Camera code in services.js:
app.factory('FileService', function() {
var images;
var IMAGE_STORAGE_KEY = 'dav-images';
function getImages() {
var img = window.localStorage.getItem(IMAGE_STORAGE_KEY);
if (img) {
images = JSON.parse(img);
} else {
images = [];
}
return images;
};
function addImage(img) {
images.push(img);
window.localStorage.setItem(IMAGE_STORAGE_KEY, JSON.stringify(images));
};
return {
storeImage: addImage,
images: getImages
}
});
app.factory('ImageService', function($cordovaCamera, FileService, $q, $cordovaFile) {
function optionsForType(type) {
var source;
switch (type) {
case 0:
source = Camera.PictureSourceType.CAMERA;
break;
case 1:
source = Camera.PictureSourceType.PHOTOLIBRARY;
break;
}
return {
quality: 90,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: source,
allowEdit: false,
encodingType: Camera.EncodingType.JPEG,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false,
correctOrientation:true
};
}
function saveMedia(type) {
return $q(function(resolve, reject) {
var options = optionsForType(type);
$cordovaCamera.getPicture(options).then(function(imageBase64) {
FileService.storeImage(imageBase64);
});
})
}
return {
handleMediaDialog: saveMedia
}
});
Camera code in controllers.js:
app.controller('CameraController', function($scope, $cordovaDevice, $cordovaFile, $ionicPlatform, $cordovaEmailComposer, $ionicActionSheet, ImageService, FileService) {
$ionicPlatform.ready(function() {
$scope.images = FileService.images();
$scope.$apply();
});
$scope.addMedia = function() {
$scope.hideSheet = $ionicActionSheet.show({
buttons: [
{ text: 'Take photo' },
{ text: 'Photo from library' }
],
titleText: 'Add images',
cancelText: 'Cancel',
buttonClicked: function(index) {
$scope.addImage(index);
}
});
}
$scope.addImage = function(type) {
$scope.hideSheet();
ImageService.handleMediaDialog(type).then(function() {
$scope.$apply();
});
}
$scope.sendEmail = function() {
if ($scope.images != null && $scope.images.length > 0) {
var mailImages = [];
var savedImages = $scope.images;
for (var i = 0; i < savedImages.length; i++) {
mailImages.push('base64:attachment'+i+'.jpg//' + savedImages[i]);
}
$scope.openMailComposer(mailImages);
}
}
$scope.openMailComposer = function(attachments) {
var bodyText = '<html><h2>My Images</h2></html>';
var email = {
to: '',
attachments: attachments,
subject: 'Devdactic Images',
body: bodyText,
isHtml: true
};
$cordovaEmailComposer.open(email, function(){
console.log('email view dismissed');
}, this);
}
});
To resolve this problem you need to compile an app with XCode.
After XCode compilation camera works correctly.
Probably, the problem with camera was caused by Ionic compilation.

Kendo UI Treelist rows disappears after editing

I use Kendo UI in ASP .NET MVC app. I have Kendo Treelist. Sometimes, after editing a row, all rows disappear, and I see only root element without child rows. Is it Kendo bug?Or I can prevent it? And when rows have disappeared, I refresh page, do the same changes and save treelist - the treelist works correctly.
var parsedXmlDataInJson = #Html.Raw(#ViewBag.XmlData); //jsonarray data
$( document ).ready(function() {
});
function ShowMessage(message,timeout) //пока сообщению пользователю в левом верхнем углу
{
var divMessage = $('#toggler');
if(divMessage.css('display') != 'none')
{
divMessage.clearQueue();
divMessage.stop();
divMessage.css('display','none');
}
if (timeout == 0)
divMessage.text(message).toggle('slow');
else
divMessage.text(message).toggle('slow').delay(timeout).toggle('slow');
}
var treelistds = new kendo.data.TreeListDataSource({ //CRUD for dataSource
transport: {
read: function(e) {
e.success(parsedXmlDataInJson);
},
update: function(e) {
var updatedItem = e.data;
$.each(parsedXmlDataInJson, function(indx, value) {
if (value.id == updatedItem.Id) {
value = updatedItem;
return false;
}
});
e.success();
},
create: function(e) {//Works for root element when editing only once - it's broke my treelist.
e.data.Id = GetId();
parsedXmlDataInJson.push(e.data);
e.success(e.data);
},
destroy: function(e) {
var updatedItem = e.data;
$.each(parsedXmlDataInJson, function(indx, value) {
if (value.id == updatedItem.Id) {
parsedXmlDataInJson.splice(indx, 1);
}
});
e.success();
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
batch: false,
schema: {
model: {
id: "Id",
parentId: "parentId",
fields: {
Id: {
type: "number",
editable: true,
nullable: false
},
parentId: {
field: "parentId",
nullable: true
}
}
}
}
});
$("#treeList").kendoTreeList({
resizable: true,
dataSource: treelistds,
toolbar: ["create"],
columns: [{
field: "typeAndAttributes",
width:400
}, {
field: "text",
title: "Текст",
}, {
field: "cData",
title: "CDATA",
}, { //my custom command
command: ["edit", "destroy", "createchild", {
name: "commentOut",
text: "commentOut",
click: function(e) {
var dataItem = this.dataItem($(e.target).closest("tr")); ///my custom command
dataItem.commentedOut = !dataItem.commentedOut;
var isCommentedOut = dataItem.commentedOut;
var childNotes = this.dataSource.childNodes(dataItem);
childNotes.forEach(function(childModel, i) //
{
childModel.commentedOut = isCommentedOut;
SetChildrenIsCommentedOut(childModel, isCommentedOut);
})
//обновляем цвет и текст кнопок у всех элементов вызывая dataBound
$("#treeList").data("kendoTreeList").refresh();
},
}, ]
}],
messages: {
commands: {
edit: "Изменить",
destroy: "Удалить",
createchild: "Добавить"
}
},
dataBound: function(e) {
this.autoFitColumn(3);
Databound(e.sender, e.sender.table.find("tr"));
},
editable: true,
editable: {
mode: "popup",
template: kendo.template($("#popup-editor").html()),
window: {
width:800
}
},
edit: function(e) { //invokes when popup open
$("#date").kendoDateTimePicker({
});
$("#cDataEditor").kendoEditor({
tools: [
"formatting", "bold", "italic", "underline", "insertUnorderedList",
"insertOrderedList", "indent", "outdent", "createLink", "unlink"
],
resizable: {
content: true,
toolbar: true,
max:350
}
});
//my custom logic. Popup contains many fileds splitted from one model field
if (!e.model.isNew()) { //split typeAndAttrubites to popup's fileds
var fileds = e.model.typeAndAttributes.split(';').
filter(function(v) {
return v !== ''
});
e.container.find("#type").val(fileds[0]);
var length = fileds.length;
for (i = 1; i < length; i++) {
var keyAndValue = fileds[i].split('=');
if (keyAndValue[0] != "id")
e.container.find("#" + keyAndValue[0].trim()).val(keyAndValue[1].trim());
else
e.container.find("#xmlId").val(keyAndValue[1].trim());
}
}
},
save: function(e) { //invokes when saving
var splitter = "; ";
var inputValue = $("input[id='type']").val().trim();
if (e.model.type !== undefined) {
e.model.typeAndAttributes = e.model.type;
} else {
e.model.typeAndAttributes = inputValue;
}
var allInputs = $(":input[data-appointment=attributes]");
allInputs.each(function(index, input) { //collect inputs in one filed
var attrName;
var attrValue;
if (input.id != "id") {
attrName = input.id;
e.model[attrName];
} else {
attrName = "id";
attrValue = e.model["xmlId"];
}
//значение изменили и оно не пустое
if (attrValue !== undefined && attrValue !== "") {
if (attrValue == false)
return true;
e.model.typeAndAttributes += splitter + attrName + "=" + attrValue;
}
//my custom logic
else if (input.value.trim() && input.value != "on") {
e.model.typeAndAttributes += splitter + attrName + "=" + input.value.trim();
}
})
}
});
//рекурсивно помечаем ряды как закомментированные или нет
function SetChildrenIsCommentedOut(dataItem, isCommentedOut) {
var childNotes = $("#treeList").data("kendoTreeList").dataSource.childNodes(dataItem);
childNotes.forEach(function(childModel, i) {
childModel.commentedOut = isCommentedOut;
SetChildrenIsCommentedOut(childModel, isCommentedOut);
})
}
//Раскрашивает строки соответственно значению закомментировано или нет
function Databound(sender, rows) {
rows.each(function(idx, row) {
var dataItem = sender.dataItem(row);
if (dataItem.commentedOut) {
//обозначаем ряд как закомментированный
$(row).css("background", "#DCFFE0");
$(row).find("[data-command='commentout']").html("Раскомментировать");
} else {
//обозначаем ряд как незакомментированный
$(row).css("background", "");
$(row).find("[data-command='commentout']").html("Закомментировать");
}
})
}
});
var currentId = 0;
function GetId() { //генерирование Id для новых записей
var dataSource = $("#treeList").data("kendoTreeList").dataSource;
do {
currentId++;
var dataItem = dataSource.get(currentId);
} while (dataItem !== undefined)
return currentId;
}

How can I resend a post/get data in case of failure?

I tried to use addProgressListener but I don't know how to get post data in onStateChange and send it back.
exports.main = function() {
var {Cc, Ci, Cu} = require("chrome");
var windows = require("sdk/windows").browserWindows;
const windowUtils = require("sdk/window/utils");
var {XPCOMUtils} = Cu.import("resource://gre/modules/XPCOMUtils.jsm");
var { setTimeout, clearTimeout } = require("sdk/timers");
var gBrowser = windowUtils.getMostRecentBrowserWindow().getBrowser();
var tabs = require("sdk/tabs");
const STATE_START = Ci.nsIWebProgressListener.STATE_START;
const STATE_STOP = Ci.nsIWebProgressListener.STATE_STOP;
const STATE_REDIRECTING = Ci.nsIWebProgressListener.STATE_REDIRECTING;
const STATE_TRANSFERRING = Ci.nsIWebProgressListener.STATE_TRANSFERRING;
const STATE_RESTORING = Ci.nsIWebProgressListener.STATE_RESTORING;
var timer = null;
var counter = 0;
var start_url = '';
var retry = false;
var myListener = {
QueryInterface: XPCOMUtils.generateQI(Ci),
onState: function(aWebProgress, aRequest, aFlag, aStatus) {
console.log('test');
},
onStateChange: function(aWebProgress, aRequest, aFlag, aStatus) {
Ci.nsIUploadChannel2
if(!aRequest.name.startsWith('http')) {
return false;
}
if (!(start_url && (start_url == aRequest.name))) {
if (!aWebProgress.isLoadingDocument && !retry) {
return false;
}
}
retry = false;
if (aFlag & STATE_START) {
if (timer) {
clearTimeout(timer);
timer = null
start_url = '';
counter = 0
}
console.log("start");
start_url = aRequest.name;
timer = setTimeout(function() {
if (counter < 5) {
// console.log("after start");
console.log("aRequest.name: ", aRequest.name);
new_tab = gBrowser.addTab(aRequest.name);
gBrowser.removeCurrentTab();
gBrowser.selectedTab = new_tab;
retry = true;
counter += 1
myListener['onStateChange'](aWebProgress, aRequest,
aFlag, aStatus);
} else {
gBrowser.removeCurrentTab();
}
}, 10000)
}
if (aFlag & STATE_STOP) {
if (timer) {
console.log("stop");
clearTimeout(timer);
timer = null
start_url = '';
counter = 0
}
}
},
onLocationChange: function(aProgress, aRequest, aURI) {
start_url = aRequest.name;
console.log('onLocationChange: ', aRequest.name)
},
onProgressChange: function(aWebProgress, aRequest, curSelf,
maxSelf, curTot, maxTot) {
console.log('onProgressChange: ', aRequest.name)
},
onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage) {
console.log('onStatusChange: ', aRequest.name)
},
onSecurityChange: function(aWebProgress, aRequest, aState) {
console.log('onSecurityChange: ', aRequest.name)
}
}
gBrowser.addProgressListener(myListener);
}
I also tried to use observerService but none of those topics makes it possible to keep track of each request and make my plans.
observerService.addObserver(this, "http-on-opening-request", false);
observerService.addObserver(this, "http-on-examine-merged-response", false);
observerService.addObserver(this, "http-on-examine-cached-responsee", false);
observerService.addObserver(this, "http-on-examine-response", false);
I assume that the data request can be obtained using nsIUploadChannel but I do not understand how to use it.
Try this, untested, didnt even check for typos.
onStateChange: function(aWebProgress, aRequest, aFlag, aStatus) {
if (aRequest instanceof Ci.nsIHttpChannel) {
if (aRequest.QueryInterface(Ci.nsIHttpChannel).uploadStream) {
// see line 10 - https://gist.github.com/Noitidart/28624e20bfee2dc128c4#file-gistfile1-txt-L10
}
}
if(!aRequest.name.startsWith('http')) {
return false;
}

Jquery autocomplete Select not working

i want to select the Autocomplete box item list . but it is not working . i have write this code to get the item. whenever i use self._renderItemData = function (ul, item) this function customized way the selection stops and when i comment this function my code works fine . please help me to know where am i wrong. i have used jquery ui 1.9 to write the code.
$(document).ready(function () {
var term = "";
var type = "";
var key = "";
$("#searchTextBox").autocomplete({
minLength: 2,
autoFocus: true,
source: function (request, response) {
$.ajax({
url: "../CustomHandlers/SearchHandler.ashx",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: { term: request.term },
success: function (data) {
if (!data || data.length == 0) {
response([{
label: "noMatched",
hcount:0,
type: "noResult",
key: "noResult"
}]);
}
else {
response($.map(data, function(item) {
return {
label: item.label,
hcount:item.record,
type: item.type,
key: item.key
}
}))
}
}
});
$.ui.autocomplete.prototype._renderMenu=function (ul, items) {
var self = this;
currentType = "";
$.each(items, function (index, item) {
if (item.type != currentType) {
ul.append("<li class='ui-autocomplete-type'>" + item.type + "</li>");
currentType = item.type;
}
self._renderItemData(ul, item);
});
self._renderItemData = function (ul, item) {
var searchhtml = "<a class='autocomplitList'>" + item.label + "<span>" + "(" + item.hcount + ") " + "</span>" + "</a>";
return $("<li></li>")
.data("item.autocomplete", item)
.append(searchhtml)
.appendTo(ul);
};
}
}
, select: function (event, ui)
{
term = ui.item.label;
type = ui.item.type;
key = ui.item.key;
// ui.item.option.selected = true;
// $("#searchTextBox").val(ui.item.label);
// return false;
//var selectedObj = ui.item.key;
// alert("Selected: " + selectedObj);
}
,open: function (event, ui) {
//event.addClass("nodis");
}
,close: function () {
// event.removeClass("nodis")
this._trigger("close");
}
});
Try this
$(document).ready(function() {
var term = "";
var type = "";
var key = "";
$.ui.autocomplete.prototype._renderMenu = function(ul, items) {
var self = this;
currentType = "";
$.each(items, function(index, item) {
if (item.type != currentType) {
ul.append("<li class='ui-autocomplete-type'>"
+ item.type + "</li>");
currentType = item.type;
}
self._renderItemData(ul, item);
});
self._renderItemData = function(ul, item) {
var searchhtml = "<a class='autocomplitList'>" + item.label
+ "<span>" + "(" + item.hcount + ") " + "</span>" + "</a>";
return $("<li></li>").data("item.autocomplete", item)
.append(searchhtml).appendTo(ul);
};
}
$("#searchTextBox").autocomplete({
minLength : 2,
autoFocus : true,
source : function(request, response) {
response([{
label : "Value 1",
hcount : 0,
type : "t1",
key : "v1"
}, {
label : "Value 2",
hcount : 0,
type : "t1",
key : "v2"
}, {
label : "Value 3",
hcount : 0,
type : "t2",
key : "v3"
}, {
label : "Value 4",
hcount : 0,
type : "t3",
key : "v4"
}]);
}
,
select : function(event, ui) {
term = ui.item.label;
type = ui.item.type;
key = ui.item.key;
// ui.item.option.selected = true;
// $("#searchTextBox").val(ui.item.label);
// return false;
// var selectedObj = ui.item.key;
// alert("Selected: " + selectedObj);
},
open : function(event, ui) {
// event.addClass("nodis");
},
close : function() {
// event.removeClass("nodis")
this._trigger("close");
}
});
$("#searchTextBox").data('autocomplete')._renderMenu = function(ul, items) {
var that = this;
var currentType = "";
$.each(items, function(index, item) {
if (item.type != currentType) {
ul.append("<li class='ui-autocomplete-type'>"
+ item.type + "</li>");
currentType = item.type;
}
$("<li></li>").addClass('newp').append($("<a></a>")
.text(item.label)).appendTo(ul).data(
"ui-autocomplete-item", item);;
});
}
});
Demo: Fiddle

How to change the value of a JQueryUI progressbar dynamically?

In my import photos script, I try to update a progressbar (Jquery UI) following a while loop with Ajax requests.
The JQueryUI progressbar, which is supposed to be displayed before the launch of ajax requests do it after. So I have the user feedback at the end of the execution of my while loop ... (The console shows me that these applications are running well, in the right order)
I thought about using live () or bind (), but I do not know how to test it ...
Here is my jquery code:
$(function() {
var percent_progressbar=0;
$('#myform').submit(function() {
$('#myform').hide();
$("#text_result").html("Import in progress : <span class='progression'>0/0</span>").show(10, function() {
$("#myprogressbar").progressbar({value:percent_progressbar});
$("#myprogressbar").show(10, function() {
if (jQuery.trim($("#id_src").val()).length!=0) {
// Total number of photos to import
$.ajax({
type : 'POST',
async : false,
url : '/nbphotos.php',
data : 'chem=mydir',
success : function(nbphotos){
if (nbphotos>0){
$(".progression").html("0"+" / "+nbphotos);
var finish=false;
var nb_photos_imported=0;
var ajax_done = false;
var resultat_ajax="";
// Variables envoyées en Ajax
var datas = desvariables;
while (nb_photos_imported < nbphotos) {
ajax_done = false;
$.ajax({
type : 'GET',
async : false,
url : '/traitement.php',
data : datas,
success : function(resultat){
resultat_ajax=resultat;
ajax_done=true;
nb_photos_imported++;
}
});
if (ajax_done==true){
if (resultat_ajax=="ok") {
percent_progressbar = Math.floor(nb_photos_imported*100/nbphotos);
$("#myprogressbar").progressbar("option", "value", percent_progressbar);
console.info("Succès ajax (resultat : OK) : "+percent_progressbar);
$(".progression").html(nb_photos_imported+" / "+nbphotos);
} else {
finish=true;
$("#text_result").html(ajax_done);
return false;
}
} else {
// ajax error => exit the while
console.info("Ajax execution error "+nb_photos_imported);
return false;
}
} // While
if (finish==true) {
$("#myprogressbar").hide('slow');
$('#text_result').html("Import of "+nb_photos_imported+" photos done.");
}
} else{
$("#text_result").html("No photo to import.");
$("#myprogressbar").hide(10);
$('#myform').show("slow");
}
}
});
}
});
}); // callback #text_result.show()
return false;
});
});
Here is my new code. The console log show the progression of the percentage, the photos are imported, but I still have the display at the end. If I put a breakpoint with me debugging tool somewhere in the loop, the display is refreshing and everything is OK...
$(function () {
$("#myprogressbar").show();
var RetourNbPhotos = "";
var RetourImported = "";
var fini = false;
var percent_progressbar = 0;
var nb_photos_imported = 0;
var datas = desvariables; // datas sent with ajax
// Number of photos to import
function NbPhotoAjax() {
return $.ajax({
type: 'POST',
async: false,
url: '/boutique/modules/importimageswithiptc/ajax-nbphotos.php',
data: 'chem=$cheminimport',
success: function (nbphotos) {
RetourNbPhotos = nbphotos;
}
});
}
// Photo Ajax Import
function ImportPhotoAjax() {
$("#text_result").html("Import in progress : <span class='progression'>0/0</span>").show();
// RetourImported = "";
return $.ajax({
type: 'GET',
async: false,
url: '/boutique/modules/importimageswithiptc/ajax-traitement.php',
data: datas,
success: function (resultat) {
RetourImported = resultat;
}
});
}
$("#myprogressbar").progressbar({
value: percent_progressbar
});
$('#generator').submit(function () {
$('#generator').hide();
if (jQuery.trim($("#id_product_src").val()).length != 0) {
$.when(NbPhotoAjax()).then(function () {
if (RetourNbPhotos > 0) {
while (nb_photos_imported < RetourNbPhotos) {
$.when(ImportPhotoAjax()).then(function () {
nb_photos_imported++;
if (RetourImported == "ok") {
percent_progressbar = Math.floor(nb_photos_imported * 100 / RetourNbPhotos);
$("#myprogressbar").progressbar("option", "value", percent_progressbar);
console.info("Success : " + percent_progressbar + "%");
$(".progression").html(nb_photos_imported + " / " + RetourNbPhotos);
} else {
fini = true;
$("#text_result").html("ajax_reussi");
return false;
}
}).fail(function () {
// ajax error => exit the while
console.info("Ajax execution error " + nb_photos_imported);
return false;
});
} // While
if (fini == true) {
$("#myprogressbar").hide('slow');
$('#text_result').html("Import of " + nb_photos_imported + " photos done.");
}
} else {
$("#text_result").html("No photo to import.");
$("#myprogressbar").hide(10);
$('#generator').show("slow");
}
});
}
return false;
});
});

Resources