This is my code :
var newMailListener = {
msgAdded: function(aMsgHdr) {
if(!aMsgHdr.isRead) {
gFolderDisplay.selectMessage(aMsgHdr);
var uri = gFolderDisplay.selectedMessageUris;
alert(uri);
msgHdr = messenger.messageServiceFromURI(uri).messageURIToMsgHdr(uri);
alert(getMessageBody(msgHdr,uri));
goDoCommand("cmd_markAsRead");
}
}
};
function init() {
var ancienmsg = null;
var notificationService = Components.classes["#mozilla.org/messenger/msgnotificationservice;1"]
.getService(Components.interfaces.nsIMsgFolderNotificationService);
notificationService.addListener(newMailListener, notificationService.msgAdded);
}
addEventListener("load", init, true);
function getMessageBody(aMessageHeader, uri)
{
let messenger = Components.classes["#mozilla.org/messenger;1"] .createInstance(Components.interfaces.nsIMessenger);
alert("charge messenger");
let listener = Components.classes["#mozilla.org/network/sync-stream-listener;1"].createInstance(Components.interfaces.nsISyncStreamListener);
alert("charge listener");
messenger.messageServiceFromURI(uri)
.streamMessage(uri, listener, null, null, false, "");
let folder = aMessageHeader.folder;
alert("initialise messenger");
return folder.getMsgTextFromStream(listener.inputStream,
aMessageHeader.Charset,
65536,
32768,
false,
true,
{ });
}
It is supposed, according to the mozilla's documentation, to display, in an alert, the body of the mail received. But, every time during the return of the getMessageBody method, thunderbird crash and I need to restart it. Does anybody have an idea of why and how to display it ?
In another Stackoverflow question, I find this and it works for me.
Components.utils.import("resource:///modules/gloda/mimemsg.js");
var newMailListener = {
msgAdded: function(aMsgHdr) {
if( !aMsgHdr.isRead ){
MsgHdrToMimeMessage(aMsgHdr, null, function (aMsgHdr, aMimeMessage) {
// do something with aMimeMessage:
alert("the message body : " + aMimeMessage.coerceBodyToPlaintext());
//alert(aMimeMessage.allUserAttachments.length);
//alert(aMimeMessage.size);
}, true);
}
}
};
But you only get the text and not the HTML.
Related
I am working on a web application, I am just using javascript at the moment. The problem that I am trying to solve is that I have three different objects and only one HTML page. Based on the user click event, I want the objects for the chosen category to be loaded and displayed on the same page. For example, let's say the user is at the home page, if they click on category A from the navigation bar, the page will be loaded first and then the script will load the objects to the data structure. Finally, display them to the javascript generated HTML containers. The same thing should happen with a different category after the User click Event is fired. To be more precise I want to be able to reuse the HTML page for different objects without having to create a page for each category.
I already have created the code that does all of the data loading and HTML generation for the n objects I want to load. The code works fine when I am at the object's page but if the event is fired from another page nothing seems to happen. I am guessing this has to do with page loading timing.
I have posted the complete code of the part that I am working on.
var dataController = (function() {
var JSONurls = {
bags: "../JSON/bags.json",
bc: "../JSON/briefcases.json",
belts: "../JSON/belts.json",
accs: "../JSON/accs.json",
};
ProductObj = function(name, des, colors, price, pics, type, ID) {
this.name = name;
this.description = des;
this.colors = colors;
this.price = price;
this.pics = pics;
this.type = type;
this.ID = ID;
};
var dataStruc = {
allProducts: {
bags: [],
briefcases: [],
belts: [],
accessories: [],
},
};
return {
addProd: function(obj) {
var newProd, ID;
if (dataStruc.allProducts[obj.type].length > 0) {
ID =
dataStruc.allProducts[obj.type][
dataStruc.allProducts[obj.type].length - 1
].ID + 1;
} else {
ID = 0;
}
newProd = new ProductObj(
obj.name,
obj.description,
obj.colors,
obj.price,
obj.pics,
obj.type,
obj.ID
);
dataStruc.allProducts[obj.type].push(newProd);
return newProd;
},
getDataStruct: function() {
return dataStruc;
},
getJsonUrls: function() {
return JSONurls;
},
loadJSON: function(url, cat, callback) {
var requestURL, request, JsonObj;
requestURL = url;
request = new XMLHttpRequest();
request.open("GET", requestURL);
request.responseType = "text";
request.send();
request.onload = function() {
JsonObj = JSON.parse(request.response);
dataStruc.allProducts[cat] = JsonObj[cat];
callback(cat);
};
},
};
})();
var UIcontroller = (function() {
var DomStrings = {
shopCatg: ".shop-catg",
productCont: ".product-container",
};
//public methods
return {
// function display the object based on the category based on the event target
displayObjectToPage: function(cat) {
var deafultHtml;
// 1. loop over the product category
dataController.getDataStruct().allProducts[cat].forEach(function(cur) {
deafultHtml =
'<div class="col-lg-4 col-md-6 col-sm-10">' +
'<img class="img-fluid" src="../img/' +
cur.type +
"/" +
cur.pics[0] +
'.jpg">' +
'<h6 class="text-center">' +
cur.name +
"</h6>" +
'<div class="text-center text-muted">' +
cur.price +
"</div>" +
"</div>";
document
.querySelector(DomStrings.productCont)
.insertAdjacentHTML("beforeend", deafultHtml);
});
},
getDomStrings: function() {
return DomStrings;
},
};
})();
var mainController = (function(UIctrl, dataCrtl) {
var setUpEvents = function() {
var doneLoading = false;
var DOM = UIctrl.getDomStrings();
document.querySelector(DOM.shopCatg).addEventListener("click", function() {
InitializeData(event, function(cat) {
UIcontroller.displayObjectToPage(cat);
});
});
};
InitializeData = function(event, callback) {
var category = event.target.textContent;
if (event.target.textContent === "bags") {
dataController.loadJSON(
dataController.getJsonUrls().bags,
category,
callback
);
} else if (event.target.textContent === "briefcases") {
dataController.loadJSON(dataController.getJsonUrls().bags, "briefcases");
} else if (event.target.textContent === "belts") {
dataController.loadJSON(dataController.getJsonUrls().bags, "belts");
} else {
dataController.loadJSON(dataController.getJsonUrls().bags, "accs");
}
};
displayObject = function() {};
return {
init: function() {
setUpEvents();
},
};
})(UIcontroller, dataController);
mainController.init();
I'm not sure, but I noticed this potential issue:
request.send();
request.onload = function() {
// ...
}
I believe when you call send, the request should start asynchronously. If the request comes back before onload is assigned, you might be seeing it get skipped. I haven't used XHR directly in years, though.
Normally you'd want to add the onload callback before calling send() to avoid this issue.
I also just noticed that you're missing the event in the arguments of the callback function here:
▽
document.querySelector(DOM.shopCatg).addEventListener("click", function() {
▽ event is undefined
InitializeData(event, function(cat) {
UIcontroller.displayObjectToPage(cat);
});
});
I have 2 function that I am trying to run, one after another. For some reason they both run at the same time, but the second one does not load properly. Is there a way to run the first function wait then run the second function?:
//run this first
$('#abc').click(function() {
$('.test1').show();
return false;
});
//run this second
(function ($) {
"use strict";
// A nice closure for our definitions
function getjQueryObject(string) {
// Make string a vaild jQuery thing
var jqObj = $("");
try {
jqObj = $(string)
.clone();
} catch (e) {
jqObj = $("<span />")
.html(string);
}
return jqObj;
}
function printFrame(frameWindow, content, options) {
// Print the selected window/iframe
var def = $.Deferred();
try {
frameWindow = frameWindow.contentWindow || frameWindow.contentDocument || frameWindow;
var wdoc = frameWindow.document || frameWindow.contentDocument || frameWindow;
if(options.doctype) {
wdoc.write(options.doctype);
}
wdoc.write(content);
wdoc.close();
var printed = false;
var callPrint = function () {
if(printed) {
return;
}
// Fix for IE : Allow it to render the iframe
frameWindow.focus();
try {
// Fix for IE11 - printng the whole page instead of the iframe content
if (!frameWindow.document.execCommand('print', false, null)) {
// document.execCommand returns false if it failed -http://stackoverflow.com/a/21336448/937891
frameWindow.print();
}
// focus body as it is losing focus in iPad and content not getting printed
$('body').focus();
} catch (e) {
frameWindow.print();
}
frameWindow.close();
printed = true;
def.resolve();
}
// Print once the frame window loads - seems to work for the new-window option but unreliable for the iframe
$(frameWindow).on("load", callPrint);
// Fallback to printing directly if the frame doesn't fire the load event for whatever reason
setTimeout(callPrint, options.timeout);
} catch (err) {
def.reject(err);
}
return def;
}
function printContentInIFrame(content, options) {
var $iframe = $(options.iframe + "");
var iframeCount = $iframe.length;
if (iframeCount === 0) {
// Create a new iFrame if none is given
$iframe = $('<iframe height="0" width="0" border="0" wmode="Opaque"/>')
.prependTo('body')
.css({
"position": "absolute",
"top": -999,
"left": -999
});
}
var frameWindow = $iframe.get(0);
return printFrame(frameWindow, content, options)
.done(function () {
// Success
setTimeout(function () {
// Wait for IE
if (iframeCount === 0) {
// Destroy the iframe if created here
$iframe.remove();
}
}, 1000);
})
.fail(function (err) {
// Use the pop-up method if iframe fails for some reason
console.error("Failed to print from iframe", err);
printContentInNewWindow(content, options);
})
.always(function () {
try {
options.deferred.resolve();
} catch (err) {
console.warn('Error notifying deferred', err);
}
});
}
function printContentInNewWindow(content, options) {
// Open a new window and print selected content
var frameWindow = window.open();
return printFrame(frameWindow, content, options)
.always(function () {
try {
options.deferred.resolve();
} catch (err) {
console.warn('Error notifying deferred', err);
}
});
}
function isNode(o) {
/* http://stackoverflow.com/a/384380/937891 */
return !!(typeof Node === "object" ? o instanceof Node : o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName === "string");
}
$.print = $.fn.print = function () {
// Print a given set of elements
var options, $this, self = this;
// console.log("Printing", this, arguments);
if (self instanceof $) {
// Get the node if it is a jQuery object
self = self.get(0);
}
if (isNode(self)) {
// If `this` is a HTML element, i.e. for
// $(selector).print()
$this = $(self);
if (arguments.length > 0) {
options = arguments[0];
}
} else {
if (arguments.length > 0) {
// $.print(selector,options)
$this = $(arguments[0]);
if (isNode($this[0])) {
if (arguments.length > 1) {
options = arguments[1];
}
} else {
// $.print(options)
options = arguments[0];
$this = $("html");
}
} else {
// $.print()
$this = $("html");
}
}
// Default options
var defaults = {
globalStyles: true,
mediaPrint: false,
stylesheet: null,
noPrintSelector: ".no-print",
iframe: true,
append: null,
prepend: null,
manuallyCopyFormValues: true,
deferred: $.Deferred(),
timeout: 750,
title: null,
doctype: '<!doctype html>'
};
// Merge with user-options
options = $.extend({}, defaults, (options || {}));
var $styles = $("");
if (options.globalStyles) {
// Apply the stlyes from the current sheet to the printed page
$styles = $("style, link, meta, base, title");
} else if (options.mediaPrint) {
// Apply the media-print stylesheet
$styles = $("link[media=print]");
}
if (options.stylesheet) {
// Add a custom stylesheet if given
$styles = $.merge($styles, $('<link rel="stylesheet" href="' + options.stylesheet + '">'));
}
// Create a copy of the element to print
var copy = $this.clone();
// Wrap it in a span to get the HTML markup string
copy = $("<span/>")
.append(copy);
// Remove unwanted elements
copy.find(options.noPrintSelector)
.remove();
// Add in the styles
copy.append($styles.clone());
// Update title
if (options.title) {
var title = $("title", copy);
if (title.length === 0) {
title = $("<title />");
copy.append(title);
}
title.text(options.title);
}
// Appedned content
copy.append(getjQueryObject(options.append));
// Prepended content
copy.prepend(getjQueryObject(options.prepend));
if (options.manuallyCopyFormValues) {
// Manually copy form values into the HTML for printing user-modified input fields
// http://stackoverflow.com/a/26707753
copy.find("input")
.each(function () {
var $field = $(this);
if ($field.is("[type='radio']") || $field.is("[type='checkbox']")) {
if ($field.prop("checked")) {
$field.attr("checked", "checked");
}
} else {
$field.attr("value", $field.val());
}
});
copy.find("select").each(function () {
var $field = $(this);
$field.find(":selected").attr("selected", "selected");
});
copy.find("textarea").each(function () {
// Fix for https://github.com/DoersGuild/jQuery.print/issues/18#issuecomment-96451589
var $field = $(this);
$field.text($field.val());
});
}
// Get the HTML markup string
var content = copy.html();
// Notify with generated markup & cloned elements - useful for logging, etc
try {
options.deferred.notify('generated_markup', content, copy);
} catch (err) {
console.warn('Error notifying deferred', err);
}
// Destroy the copy
copy.remove();
if (options.iframe) {
// Use an iframe for printing
try {
printContentInIFrame(content, options);
} catch (e) {
// Use the pop-up method if iframe fails for some reason
console.error("Failed to print from iframe", e.stack, e.message);
printContentInNewWindow(content, options);
}
} else {
// Use a new window for printing
printContentInNewWindow(content, options);
}
return this;
};
})(jQuery);
How would I run the first one wait 5 or so seconds and then run the jquery print? I'm having a hard time with this. So the id would run first and then the print would run adter the id="abc" Here is an example of the code in use:
<div id="test">
<button id="abc" class="btn" onclick="jQuery.print(#test1)"></button>
</div>
If I understand your problem correctly, you want the jQuery click function to be run first, making a div with id="test1" visible and then, once it's visible, you want to run the onclick code which calls jQuery.print.
The very first thing I will suggest is that you don't have two different places where you are handling the click implementation, that can make your code hard to follow.
I would replace your $('#abc').click with the following:
function printDiv(selector) {
$(selector).show();
window.setTimeout(function () {
jQuery.print(selector);
}, 1);
}
This function, when called, will call jQuery.show on the passed selector, wait 1ms and then call jQuery.print. If you need the timeout to be longer, just change the 1 to whatever you need. To use the function, update your example html to the following:
<div id="test">
<button id="abc" class="btn" onclick="printDiv('#test1')"</button>
</div>
When the button is clicked, it will now call the previously mentioned function and pass it the ID of the object that you want to print.
As far as your second function goes, where you have the comment **//run this second**, you should leave that alone. All it does is extend you jQuery object with the print functionality. You need it to run straight away and it currently does.
I use pjax to ajaxify my menu links. This works fine until I use the browser back button. In my javascript file I use Common Script files (to load all the necessary js files when the user hits the url) and Script files with respect to each menu links (when navigated through pjax)
function myFunction(){
/*All the script files */
}
$(document).ready(function(){
myFunction();
/*pjax menu loading block*/
$(document).on('click', 'a[data-pjax]', function(event) {
$.pjax.click(event, '#pjax-container');
$(document).on('pjax:end', function() {
myFunction();
});
});
});
Now when I navigate to a menu item and try to come back by clicking the browser back button, the script files are getting duplicated (eg: slider images getting duplicated and table sorting not working).How to overcome this issue?
You can implement the url specific loading this way, create a queue of functions which you want to load and unload on pjax complete
The solution is based on js prototyping
// create queue for load and unload
var onLoad = new PjaxExecQueue();
var onUnload = new PjaxExecQueue();
// way to add functions to queue to run on pjax load
onLoad.queue(function() {
someFunction();
});
// way to add functions to queue to unload on pjax load
onUnload.queue(function() {
someOtherFunction();
});
// load function if url contain particular path name
onLoad.queue_for_url(function_name, 'url_section');
// check for url specific function
var URLPjaxQueueElement = function(exec_function, url) {
this.method = exec_function;
if(url) {
this.url = new RegExp(url);
} else {
this.url = /.*/;
}
};
// create a queue object
var PjaxExecQueue = function () {
this.url_exec_queue = [];
this.id_exec_queue = [];
this.fired = false;
this.indicating_loading = false;
this.content = $('#content');
};
PjaxExecQueue.prototype = {
queue: function (exec_function) {
this.url_exec_queue.unshift(new URLPjaxQueueElement(exec_function));
},
queue_for_url: function (exec_function, url_pattern) {
this.url_exec_queue.unshift(new URLPjaxQueueElement(exec_function, url_pattern));
},
queue_if_id_present: function(exec_function, id) {
this.id_exec_queue.unshift(new IDPjaxQueueElement(exec_function, id));
},
fire: function () {
if(this.indicating_loading) {
this.content.removeClass("indicate-loading");
this.indicating_loading = false;
}
if(!this.fired) {
var match_loc = window.location.pathname;
var i = this.url_exec_queue.length;
while(i--) {
this.url_exec_queue[i].fire(match_loc);
}
i = this.id_exec_queue.length;
while(i--) {
this.id_exec_queue[i].fire(match_loc);
}
}
this.fired = true;
},
reset: function() {
this.fired = false;
},
loading: function () {
this.content.addClass("indicate-loading");
this.indicating_loading = true;
this.reset();
},
count: function () {
return exec_queue.length;
},
show: function (for_url) {
for (var i=0; i < exec_queue.length; i++) {
if(for_url) {
if(exec_queue[i].url.test(for_url)) {
console.log("" + exec_queue[i].method);
}
} else{
console.log(exec_queue[i].url + " : " + exec_queue[i].method);
}
}
}
};
// before send
$(document).on('pjax:beforeSend', function() {
onLoad.loading();
onUnload.fire();
});
// after pjax complete
$(document).on('pjax:complete', function() {
onLoad.fire();
onUnload.reset();
});
With alot of help from #kalley we have found out that If I comment the following two lines out the LAG is gone!
var $tableContents = $table.find('tbody')
var $html = $('<tbody/>').html(data);
But how do I keep the above but cancel out the LAG ?
MORE INFO:
The code below works but the problem is that the $.GET is causing the browser to hang until the ajax request completes. I need (flow control?) or something that will solve this problem without locking/hanging up the browser until ajax completes the GET request.
The biggest LAG/Lockup/Hang is at $.get("updatetable.php", since the others only return 7 or less (number) values and this one ('updatetable.php') returns alot more (200-300kb). I would like to implement some sort of flow control here or make the script wait like 5 secs before firing the update command for tablesort and before showing the toast message so that ajax has time to GET the $.get("updatetable.php"data I just don't understand why does it lockup the browser as it is getting the data? is it trying to fire the other commands and that's whats causing the LAG?
Here are the STEPS
1.
$.get("getlastupdate.php" Will fire every 10 secs or so to check if the date and time are the same the return data looks like this: 20130812092636 the format is: YYYmmddHHmmss.
2.
if the date and time are not the same as the last GET then $.get("getlastupdate2.php" will trigger and this data will be send back and placed into a toast message and dispalyed to the user $().toastmessage('showNoticeToast', Vinfoo);
3.
before or after the above ($.get("getlastupdate2.php") another GET will fire: $.get('updatetable.php' this will GET the updated table info. and replace the old one with the new info. and then update/resort the table
4.
at the end of it all I want to $.get("ajaxcontrol.php" and this will return a 1 or 2 if the user is logged in then it will be a 2 else it's a 1 and it will destroy the session and log the user out.
<script type="text/javascript" src="tablesorter/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="tablesorter/final/jquery.tablesorter.js"></script>
<script type="text/javascript" src="tablesorter/final/jquery.tablesorter.widgets.js"></script>
<script type="text/javascript" src="tablesorter/final/toastmessage/jquery.toastmessage-min.js"></script>
<script type="text/javascript" src="tablesorter/qtip/jquery.qtip.min.js"></script>
<script type="text/javascript">
var comper;
function checkSession() {
return $.get("ajaxcontrol.php", function (DblIn) {
console.log('checking for session');
if (DblIn == 1) {
window.location = 'loggedout.php';
}
}).then(updateTable);
}
function checkComper() {
var SvInfo;
var onResponse = function (comperNow) {
if (comper === undefined) {
comper = comperNow;
} else if (comper !== comperNow) {
var Vinfoo;
comper = comperNow;
// returning this $.get will make delay done until this is done.
return $.get("getlastupdate2.php", function (primaryAddType) {
Vinfoo = primaryAddType;
$().toastmessage('showNoticeToast', Vinfoo);
}).then(checkSession);
}
};
$.get('getlastupdate.php').then(onResponse).done(function () {
tid = setTimeout(checkComper, 2000);
});
}
function updateTable() {
return $.get('updatetable.php', function (data) {
console.log('update table');
var $table = $("table.tablesorter");
var $tableContents = $table.find('tbody')
var $html = $('<tbody/>').html(data);
$tableContents.replaceWith('<tbody>' + data + '</tbody>')
//$tableContents.replaceWith($html)
$table.trigger("update", [true]);
var currentUrl = document.getElementById("frmcontent").contentWindow.location.href;
var urls = ['indexTOM.php', 'index1.php'],
frame = document.getElementById('frmcontent').contentDocument;
for (var i = 0; i < urls.length; i++) {
var url = urls[i];
if (frame.location.href.indexOf(url) !== -1) {
frame.location.reload()
}
}
$('[title!=""]').qtip({});
});
};
$(function () {
var tid = setTimeout(checkComper, 2000);
$("#append").click(function (e) {
// We will assume this is a user action
e.preventDefault();
updateTable();
});
// call the tablesorter plugin
$("table.tablesorter").tablesorter({
theme: 'blue',
// hidden filter input/selects will resize the columns, so try to minimize the change
widthFixed: true,
// initialize zebra striping and filter widgets
widgets: ["saveSort", "zebra", "filter"],
headers: {
8: {
sorter: false,
filter: false
}
},
widgetOptions: {
filter_childRows: false,
filter_columnFilters: true,
filter_cssFilter: 'tablesorter-filter',
filter_filteredRow: 'filtered',
filter_formatter: null,
filter_functions: null,
filter_hideFilters: false, // true, (see note in the options section above)
filter_ignoreCase: true,
filter_liveSearch: true,
filter_reset: 'button.reset',
filter_searchDelay: 300,
filter_serversideFiltering: false,
filter_startsWith: false,
filter_useParsedData: false
}
});
// External search
$('button.search').click(function () {
var filters = [],
col = $(this).data('filter-column'), // zero-based index
txt = $(this).data('filter-text'); // text to add to filter
filters[col] = txt;
$.tablesorter.setFilters($('table.hasFilters'), filters, true); // new v2.9
return false;
});
});
</script>
Maybe instead of using setInterval, you should consider switching to setTimeout. It will give you more control over when the time repeats:
function checkComper() {
var SvInfo;
var onResponse = function (comperNow) {
if (comper === undefined) {
comper = comperNow;
} else if (comper !== comperNow) {
var Vinfoo;
comper = comperNow;
// returning this $.get will make delay done until this is done.
return $.get("getlastupdate2.php", function (primaryAddType) {
Vinfoo = primaryAddType;
$().toastmessage('showNoticeToast', Vinfoo);
}).then(checkSession);
}
};
$.get('getlastupdate.php').then(onResponse).done(function () {
tid = setTimeout(checkComper, 10000);
});
}
var tid = setTimeout(checkComper, 10000);
Then you can keep it async: true
Here's a fiddle showing it working using echo.jsontest.com and some fudging numbers.
Since the click event callback seems to be where the issue is, try doing this and see if it removes the lag (I removed other comments to make it more brief):
function checkSession() {
return $.get("ajaxcontrol.php", function (DblIn) {
console.log('checking for session');
if (DblIn == 1) {
window.location = 'loggedout.php';
}
}).then(updateTable);
}
function updateTable() {
return $.get('updatetable.php', function (data) {
console.log('update table');
var $tableContents = $table.find('tbody')
//var $html = $('<tbody/>').html(data);
//$tableContents.replaceWith($html);
// replaceWith text seems to be much faster:
// http://jsperf.com/jquery-html-vs-replacewith/4
$tableContents.replaceWith('<tbody'> + data + '</tbody>');
//$table.trigger("update", [true]);
var currentUrl = document.getElementById("frmcontent").contentWindow.location.href;
var urls = ['indexTOM.php', 'index1.php'],
frame = document.getElementById('frmcontent').contentDocument;
for (var i = 0; i < urls.length; i++) {
var url = urls[i];
if (frame.location.href.indexOf(url) !== -1) {
frame.location.reload()
}
}
$('[title!=""]').qtip({});
});
};
$("#append").click(function (e) {
// We will assume this is a user action
e.preventDefault();
updateTable();
});
I commented out $table.trigger("update", [true]) since if you sort the table on the server before you return it, you shouldn't need to run that, which I'm almost certain is where the bottleneck is.
It is really hard untangle the mess you have but if what you want is ajax requests every 10 seconds it make sense to separate this logic from business logic over data from server.
Your code would also really benefit from using promises. Consider this example
$(document).ready(function() {
var myData = { }
, ajaxPromise = null
setInterval(callServer, 1000)
function callServer() {
ajaxPromise = updateCall()
.then(controlCall)
.done(handler)
.error(errorHandler)
}
function updateCall() {
return $.get('updateTable.php', function(data) {
myData.update = data
})
}
function controlCall( ) {
return $.get('ajaxControl.php', function(data) {
myData.control = data
})
}
function handler() {
console.dir(myData)
}
function errorHandler(err) {
console.log(err)
console.dir(myData)
}
})
I'm writing some form validation functions, and I've decided to go with jQueryUI for prompting the user because of flexibility.
There is a slight problem tho. I want my functions to return an array which consists of a boolean and a string for my error reporting system. JQueryUI dialogs are asynchronous which means the browser won't hang and wait for a return value as the native prompt() would.
Here is some sample code:
Validator function:
function verifyTOS_PVM_v2()
{
verifyTOS_PVM_v2_callback = '';
if(!empty($('#inputPVM').val())) {
$('#inputPVM').val(date('d.m.Y', parseFinnishDate($('#inputPVM').val())));
val = $('#inputPVM').val()
date = parseFinnishDate($('#inputPVM').val());
today = today();
diff = Math.floor((date - today)/60/60/24);
if(diff <= -14)
{
buttons =
[
{
text:"Kyllä",
click:function()
{
$(this).dialog('destroy');
verifyTOS_PVM_v2_callback = "Kyllä"
}
},
{
text:"Ei",
click:function()
{
$(this).dialog('destroy');
verifyTOS_PVM_v2_callback = "Ei"
}
}
]
jQueryPrompt('Message', 'Koskien päivämäärää...', 400, buttons);
while(verifyTOS_PVM_v2_callback != "Kyllä" && verifyTOS_PVM_v2_callback != "Ei")
{
setTimeout('i = i + 1', 50)
}
res = verifyTOS_PVM_v2_callback;
if(res == "Kyllä")
{
error_occured = 2;
error = 'Message'
}
else
{
error_occured = 1;
error = 'Message'
}
}
} else {
error_occurred = 1;
error = "Message";
}
reterr[0] = error_occurred;
reterr[1] = error;
return reterr;
}
Prompt function:
function jQueryPrompt(msg, title, width, buttons)
{
$('body').append('<div id="jQueryPromptHost"></div>');
$('#jQueryPromptHost').append(msg);
$('#jQueryPromptHost').dialog({
title: title,
resizable: false,
width: width,
daraggable: false,
modal: true,
buttons: buttons
})
}
I have tried polling for a variable and that failed miserably (firefox just hanged and took more memory for itself...)
Do you have any suggestions?
Regards,
Akke
EDIT:
I have picked another approach to this problem. I marked the closest solution as the answer, in case someone else picks his approach. Thank you all!
In your click event handler simply call a function instead of assigning a value.
buttons = [
{
text:"Kyllä",
click: function() {
$(this).dialog('destroy');
handleButtonClick("Kyllä");
//verifyTOS_PVM_v2_callback = "Kyllä"
}
},
{
text:"Ei",
click: function() {
$(this).dialog('destroy');
handleButtonClick("Ei");
//verifyTOS_PVM_v2_callback = "Ei"
}
}
]
//Somewhere else in the code
var handleButtonClick = function(value) {
if (value == "Kyllä") {
...
} else if (value == "Ei") {
...
}
};
while loop is locking, you can not use it.
Going to have to break up the function into two parts. First part is code before you call the dialog, second part is the part after the dialog. The dialog button clicks call the second function.
If the code has to be synchronous, you are sort of out of luck and stuck with the ugly window.prompt.