Browser freezing for a couple of second - javascript

When the following codes are running, it makes the browser freeze for a couple of secondes.
How could i prevent that ? Thanks
function rsfp_changePage(formId, page, totalPages, validate)
{
if (validate)
{
var form = rsfp_getForm(formId);
if (!ajaxValidation(form, page))
return false;
}
for (var i=0; i<=totalPages; i++)
{
var thePage = document.getElementById('rsform_' + formId + '_page_' + i);
if (thePage)
document.getElementById('rsform_' + formId + '_page_' + i).style.display = 'none';
}
var thePage = document.getElementById('rsform_' + formId + '_page_' + page);
if (thePage)
{
thePage.style.display = '';
try {
eval('if (typeof rsfp_showProgress_' + formId + ' == "function") rsfp_showProgress_' + formId + '(' + page + ')');
}
catch (err) { }
}
}
...
You will find the form on http://www.ocsl.ch/dev
username : stackoverflow /
password : stackoverflow
Login first and then go to http://www.ocsl.ch/dev/sejour-linguistique/adultes/demande-d-offre-en-ligne
Once on this page, click on the green button "suivant" and you will see that it freezes for a very little will.
Below the content form the script.js file which contain the ajaxvalidation fonction.
Hope that helps a bit. Please ask if you need any thing else that may help.
function refreshCaptcha(componentId, captchaPath)
{
if(!captchaPath) captchaPath = 'index.php?option=com_rsform&task=captcha&componentId=' + componentId;
document.getElementById('captcha' + componentId).src = captchaPath + '&' + Math.random();
document.getElementById('captchaTxt' + componentId).value='';
document.getElementById('captchaTxt' + componentId).focus();
}
function number_format(number, decimals, dec_point, thousands_sep)
{
var n = number, prec = decimals;
n = !isFinite(+n) ? 0 : +n;
prec = !isFinite(+prec) ? 0 : Math.abs(prec);
var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
var dec = (typeof dec_point == "undefined") ? '.' : dec_point;
var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
var abs = Math.abs(n).toFixed(prec);
var _, i;
if (abs >= 1000) {
_ = abs.split(/\D/);
i = _[0].length % 3 || 3;
_[0] = s.slice(0,i + (n < 0)) +
_[0].slice(i).replace(/(\d{3})/g, sep+'$1');
s = _.join(dec);
} else {
s = s.replace('.', dec);
}
return s;
}
function buildXmlHttp()
{
var xmlHttp;
try
{
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}
function ajaxValidation(form, page)
{
try
{
var el = form.elements.length;
}
catch (err)
{
form = this;
}
var xmlHttp = buildXmlHttp();
var url = 'index.php?option=com_rsform&task=ajaxValidate';
if (page)
url += '&page=' + page;
var params = new Array();
var submits = new Array();
var success = false;
var formId = 0;
for (i=0; i<form.elements.length; i++)
{
// don't send an empty value
if (!form.elements[i].name) continue;
if (form.elements[i].name.length == 0) continue;
// check if the checkbox is checked
if (form.elements[i].type == 'checkbox' && form.elements[i].checked == false) continue;
// check if the radio is selected
if (form.elements[i].type == 'radio' && form.elements[i].checked == false) continue;
if (form.elements[i].type == 'submit')
{
submits.push(form.elements[i]);
form.elements[i].disabled = true;
}
// check if form is a dropdown with multiple selections
if (form.elements[i].type == 'select-multiple')
{
for (var j=0; j<form.elements[i].options.length; j++)
if (form.elements[i].options[j].selected)
params.push(form.elements[i].name + '=' + encodeURIComponent(form.elements[i].options[j].value));
continue;
}
if (form.elements[i].name == 'form[formId]')
formId = form.elements[i].value;
params.push(form.elements[i].name + '=' + encodeURIComponent(form.elements[i].value));
}
params = params.join('&');
xmlHttp.open("POST", url, false);
//Send the proper header information along with the request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
var success = true;
if (xmlHttp.responseText.indexOf("\n") != -1)
{
var response = xmlHttp.responseText.split("\n");
// All spans set to no error
var ids = response[0].split(',');
for (var i=0; i<ids.length; i++)
if (!isNaN(parseInt(ids[i])) && document.getElementById('component'+ids[i]))
document.getElementById('component'+ids[i]).className = 'formNoError';
// Show errors
var ids = response[1].split(',');
for (var i=0; i<ids.length; i++)
if (!isNaN(parseInt(ids[i])) && document.getElementById('component'+ids[i]))
{
document.getElementById('component'+ids[i]).className = 'formError';
success = false;
}
if (response.length == 4)
{
page = parseInt(response[2]) - 1;
totalPages = parseInt(response[3]);
rsfp_changePage(formId, page, totalPages, false);
}
for (var i=0; i<submits.length; i++)
submits[i].disabled = false;
}
if (success == false && document.getElementById('rsform_error_' + formId))
{
try {
document.getElementById('rsform_error_' + formId).style.display = '';
}
catch (err) { }
}
return success;
}
function rsfp_addEvent(obj, evType, fn){
if (obj.addEventListener){
obj.addEventListener(evType, fn, false);
return true;
} else if (obj.attachEvent){
var r = obj.attachEvent("on"+evType, fn);
return r;
} else {
return false;
}
}
function rsfp_getForm(formId)
{
var formIds = document.getElementsByName('form[formId]');
for (var i=0; i<formIds.length; i++)
{
if (parseInt(formIds[i].value) != parseInt(formId))
continue;
var form = formIds[i].parentNode;
if (form.tagName == 'FORM' || form.nodeName == 'FORM')
return form;
while (form.parentNode)
{
form = form.parentNode;
if (form.tagName == 'FORM' || form.nodeName == 'FORM')
return form;
}
}
}
Thanks #JuanMendes, it didn't help unfortunately. I made some reaserch to find out how could I modify the codes to send an asynchronous request but I didn't succeed. In the ajaxValidation fonction, there is
xmlHttp.open("POST", url, false);
if I change it to
xmlHttp.open("POST", url, true);
it should then be an asynchronous request, isn't it.
When I tested it, it didn't freeze the browser, however it doesn't show the error if fields are not filled up on the form. Instead, it validates which is not mean to be. Any help ?

As IAbstractDownvoteFactory mentioned, you're probably calling ajax in synchronous mode, which means exactly that, freeze the screen while you're waiting for the network call.
The reason it looks that way is that your ajaxValidation is returning a value. Typically, you would send an asynchronous request and your ajaxValidation would take a callback. Then the UI won't hang waiting for the XHR.
// This is an improvement over what you had
// Still poor code, since it's hard to tell what the function is doing
function rsfp_changePage(formId, page, totalPages, validate)
{
var form = rsfp_getForm(formId);
if (validate) {
// Change your AJAX validation function to take a callback, which passes the return
// value (asynchronous) instead of relying on a return value (synchronous)
ajaxValidation(form, page, function(validationResult){
if (validationResult) {
showProgress();
}
});
} else {
showProgress();
}
function showProgress() {
for (var i=0; i<=totalPages; i++) {
var thePage = document.getElementById('rsform_' + formId + '_page_' + i);
if (thePage) {
thePage .style.display = 'none';
}
var thePage = document.getElementById('rsform_' + formId + '_page_' + page);
if (thePage) {
thePage.style.display = '';
// Don't use eval, use window and bracket to avoid it
var func = window["rsfp_showProgress_" + formId];
if (typeof func == "function") {
func(page);
}
}
}
}
}

Related

convert object to string in Javascript

UPDATED QUESTION
here is my code :
function BillerDetails() {
var iState = _xmlCFHttp.readyState;
var sStatus = "";
if (iState == 4) {
if (_xmlCFHttp.responseXML.xml != "") {
var $accNum = $("#CXACNUM");
var $accNme = $("#CXACNAM");
_xmlCFRecv.loadXML(_xmlCFHttp.responseXML.xml);
sStatus = _xmlCFRecv.selectSingleNode("/result/status").text;
if (sStatus == "1") {
if ($("#CXCLRCD option[value='" + $(this).children("Data1").text() + "']").length == 0) {
$("#CXACNUM").val($("#CXACNUM").val("Data5"));
$("#CXACNAM").val($("#CXACNAM").val("Data4"));
}
} else {
var msg = _xmlCFRecv.selectSingleNode("/result/message").text;
if (msg != "") {
alert(msg);
}
}
}
}
}
Data4 and Data5 is a field inside the database. these need to be display in the textbox. however as previous, it return output at the textbox as below :
Object Object
However when it display, it give me output :
[Object object]
This is because you are setting the returned value of val back to the same input, which is a jquery object
You need to simply do
$("#CXACNUM").val( JSON.stringify( Data5 ) );
Try using JSON.stringify as
$("#CXACNUM").val(JSON.sringify(Data5));
function BillerDetails() {
var iState = _xmlCFHttp.readyState;
var sStatus = "";
if (iState == 4) {
if (_xmlCFHttp.responseXML.xml != "") {
var $accNum = $("#CXACNUM");
var $accNme = $("#CXACNAM");
_xmlCFRecv.loadXML(_xmlCFHttp.responseXML.xml);
sStatus = _xmlCFRecv.selectSingleNode("/result/status").text;
if (sStatus == "1") {
if ($("#CXCLRCD option[value='" + $(this).children("Data1").text() + "']").length == 0) {
var Data4Val=$(this).children("Data4").text();
var Data5Val=$(this).children("Data5").text();
$("#CXACNUM").val($("#CXACNUM").val(Data5Val));
$("#CXACNAM").val($("#CXACNAM").val(Data4Val));
}
} else {
var msg = _xmlCFRecv.selectSingleNode("/result/message").text;
if (msg != "") {
alert(msg);
}
}
}
}
}
i have updated your code. hope this will work

four repeating letters check javascript, spam detection

Is there a a "smarter" way to do this? This works but I imagine has something to do with for loops, what if I was checking for 20 repeating characters?
What happens if javascript is disabled?
Is there an easier way to check for "sensical" posts instead of say aldjfalkfja;lfjaklfjlkfj how would I filter that out without storing a library of words and comparing the string to those?
function counter(){
this.value = 0;
}
var count = new counter();
function updatecount(fnc){
fnc.value = count.value + 1;
}
function charbank1(){
this.value = "";
}
var cb1 = new charbank1();
function insertchar1(fnc){
fnc.value = cb1.value + String.fromCharCode(keynum);
}
function charbank2(){
this.value = "";
}
var cb2 = new charbank2();
function insertchar2(fnc){
fnc.value = cb2.value + String.fromCharCode(keynum);
}
function charbank3(){
this.value = "";
}
var cb3 = new charbank3();
function insertchar3(fnc){
fnc.value = cb3.value + String.fromCharCode(keynum);
}
function charbank4(){
this.value = "";
}
var cb4 = new charbank4();
function insertchar1(fnc){
fnc.value = cb4.value + String.fromCharCode(keynum);
}
function repeatingcharcheck(){
if(count.value < 4){
if(count.value == 1){
insertchar1(cb1);
}
if(count.value == 2){
insertchar2(cb2);
}
if(count.value == 3){
insertchar3(cb3);
}
if(count.value == 4){
insertchar4(cb4);
}
}else{
if(cb1.value == cb2.value == cb3.value == cb4.value){
alert('four letters in a row is not allowed');
window.location.replace('somewhere.com');
}
}
}

Else-if syntax error?

var to = ['user1', '#user2', 'user3#email.com']
The following codeset should keep 'user1' in the to array, remove the '#' from the start of '#user2', and move 'user3#email.com' to the toEmail array
Right now, else if (toName[j] == '#') { is logging 'syntax error'
var toEmail = [];
var pushToEmail;
for (i=0; i<to.length; i++) {
var pushToEmail = false;
var toName = to[i];
for (j=0; j<toName.length; j++) {
if (toName[0] == '#') {
toName[0] = toName[0].replace(/#/g, ''); // remove '#''
}
console.log('toName[0] = ' + toName[0]);
else if (toName[j] == '#') {
pushToEmail = true;
break;
}
}
if (pushToEmail == true) {
toEmail += to.splice(INDEX, 1)[i];
}
}
You have a syntax error. You can't just throw a console.log in the space between an if and an else. The else has to be attached to an if statement, you've tried to attach that else to a console.log.

Any Good Number Picker for JQuery (or Javascript)?

Are there any good number picker for jquery (or standalone js)?
I would like a number picker where there is a max and min number that the user can choose from. Also, it have other options such as displaying odd number or even number or prime number or a range of number whereby some numbers in between are skipped.
Using a select to do this you can create an array with the numbers to skip and do a for loop to write the options:
int minNumber = 0;
int maxNumber = 10;
int[] skipThese = { 5, 7 };
for (int i = minNumber; i <= maxNumber; i++)
{
if(!skipThese.Contains(i)) Response.Write(String.Concat("<option value=\"", i, "\">", i, "</option>"));
}
You can do this with razor or any other way to output the HTML.
You can also do this with jQuery, dynamicaly, following the same idea:
$(document).ready(function() {
var minNumber = 0;
var maxNumber = 10;
var skipThese = [5, 7];
for (var i = minNumber; i <= maxNumber; i++) {
if ($.inArray(i, skipThese) == -1) $('#selectListID').append("<option value=\"" + i + "\">" + i + "</option>");
}
});
Edit:
Or you can use the C# code above in an aspx page and load it with AJAX from the page:
Create a select box in the page:
<select name="numPicker" id="numPicker">
<option>Loading...</option>
</select>
In a script in this page you could use jQuery's ajax() to fetch the data and populate the <select>:
$(document).ready(function() {
var numPickerSelect = $("#numPicker");
$.ajax({
url: 'url/to/page.aspx',
type: 'post'
success: function(data) {
numPickerSelect.find('option').remove(); // Remove the options in the select field
numPickerSelect.append(data); // Load the content generated by the server into the select field
},
error: function() {
alert('An error has ocurred!');
}
});
//Or use this (not sure if will work)
numPickerSelect.load("url/to/page.aspx");
});
I have used this. You should be able to modify to add extra options such as min and max fairly easily.
// Make a control only accept numeric input
// eg, $("#myedit").numeric()
// $("#myedit").numeric({alow: ' ,.'})
// $("#myedit").numeric({decimals: 2})
(function($) {
$.fn.alphanumeric = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
p = $.extend({
ichars: "!##$%^&*()+=[]\\\';,/{}|\":<>?~`.- ",
nchars: "",
allow: "",
decimals: null
}, p);
return this.each
(
function() {
if (p.nocaps) p.nchars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (p.allcaps) p.nchars += "abcdefghijklmnopqrstuvwxyz";
s = p.allow.split('');
for (i = 0; i < s.length; i++) if (p.ichars.indexOf(s[i]) != -1) s[i] = "\\" + s[i];
p.allow = s.join('|');
var reg = new RegExp(p.allow, 'gi');
var ch = p.ichars + p.nchars;
ch = ch.replace(reg, '');
var dp = p.decimals;
var isInteger = function(val) {
var objRegExp = /(^-?\d\d*$)/;
return objRegExp.test(val);
};
var isNumeric = function(val) {
// If the last digit is a . then add a 0 before testing so if they type 25. it will be accepted
var lastChar = val.substring(val.length - 1);
if (lastChar == ".") val = val + "0";
var objRegExp = new RegExp("^\\s*-?(\\d+(\\.\\d{1," + dp + "})?|\\.\\d{1," + dp + "})\\s*$", "g");
if (dp == -1)
objRegExp = new RegExp("^\\s*-?(\\d+(\\.\\d{1,25})?|\\.\\d{1,25})\\s*$", "g");
var result = objRegExp.test(val);
return result;
};
$(this).blur(function(e) {
var text = $(this).val();
if (dp != null) {
if (dp == 0) {
if (!isInteger(text)) {
$(this).val('');
e.preventDefault();
}
}
else {
if (!isNumeric(text)) {
$(this).val('');
e.preventDefault();
}
}
} else {
var c = text.split('')
for (i = 0; i < text.length; i++) {
if (ch.indexOf(c[i]) != -1) {
$(this).val('');
e.preventDefault();
};
}
}
});
$(this).keypress
(
function(e) {
switch (e.which) {
//Firefox fix, for ignoring specific presses
case 8: // backspace key
return true;
case 46: // delete key
return true;
};
if (dp != null) {
if (e.which == 32) { e.preventDefault(); return false; }
var range = getRange(this);
var typed = String.fromCharCode(e.which);
var text = $(this).val().substr(0, range.start) + typed + $(this).val().substr(range.start);
if (dp == 0) {
if (!isInteger(text)) e.preventDefault();
}
else {
if (!isNumeric(text)) e.preventDefault();
}
return;
}
if (!e.charCode) k = String.fromCharCode(e.which);
else k = String.fromCharCode(e.charCode);
if (ch.indexOf(k) != -1) e.preventDefault();
if (e.ctrlKey && k == 'v') e.preventDefault();
}
);
$(this).bind('contextmenu', function() { return false });
}
);
};
$.fn.numeric = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
var az = "abcdefghijklmnopqrstuvwxyz";
az += az.toUpperCase();
var opts = {};
if (!isNaN(p)) {
opts = $.extend({
nchars: az
}, { decimals: p });
} else {
opts = $.extend({
nchars: az
}, p);
}
return this.each(function() {
$(this).alphanumeric(opts);
}
);
};
$.fn.integer = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
var az = "abcdefghijklmnopqrstuvwxyz";
az += az.toUpperCase();
p = {
nchars: az,
allow: '-',
decimals: 0
};
return this.each(function() {
$(this).alphanumeric(p);
}
);
};
$.fn.alpha = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
var nm = "1234567890";
p = $.extend({
nchars: nm
}, p);
return this.each(function() {
$(this).alphanumeric(p);
}
);
};
})(jQuery);

regex with urls

I check if a given url matches another one (which can have wildcards).
E.g. I have the following url:
john.doe.de/foo
I'd now like to check whether the url is valid or not, the user defines the string to check with, e.g:
*.doe.de/*
That works fine, but with the following it should NOT work but it gets accepted:
*.doe.de
Here the function i wrote till now, the urls are stored as firefox prefs and i the "checkedLocationsArray" containts all urls to be checked.
function checkURLS(index)
{
if(index >= 0)
{
var pos = getPos("URL-Mask");
var url = tables[index][pos];
if(url != null && url != "")
{
var urlnow = "";
if(redlist_pref.prefHasUserValue("table.1"))
{
var checkedLocationsArray = new Array();
for(i = 0; i < tables.length; i++)
{
checkedLocationsArray[i] = tables[i][pos];
}
for(i=0;i<checkedLocationsArray.length;i++)
{
urlnow = checkedLocationsArray[i];
if(urlnow == url)
{
return true;
}
if(urlnow.indexOf('*.') != -1)
{
while(urlnow.indexOf("*.") != -1)
urlnow = urlnow.replace("\*.", "\.[^\.]*");
}
if(urlnow.indexOf('.*') != -1)
{
while(urlnow.indexOf(".*") != -1)
urlnow = urlnow.replace(".\*", "([^\.]*\.)");
}
if(urlnow.indexOf('/*') != -1)
{
while(urlnow.indexOf("/*") != -1)
urlnow = urlnow.replace("/*", /\S\+*/)
}
else if(url.lastIndexOf('/') != -1)
{
return false;
}
var regex = new RegExp(urlnow);
var Erg = regex.exec(url);
if(Erg != null)
return true;
}
}
return false;
}
}
}
i think the "else if(url.indexOf('/') != -1)" is the important part. It should work just fine like that, if I alert it I even get that the result is true but it seems like the if is not being executed..
If anything is unclear, please just post a comment. Thanks in advance!
Why don't you just add the characters for beginning and end of string?
function checkURLS(index)
{
if(index >= 0)
{
var pos = getPos("URL-Mask");
var url = tables[index][pos];
if(url != null && url != "")
{
var urlnow = "";
if(redlist_pref.prefHasUserValue("table.1"))
{
var checkedLocationsArray = new Array();
for(i = 0; i < tables.length; i++)
{
checkedLocationsArray[i] = tables[i][pos];
}
for(i=0;i<checkedLocationsArray.length;i++)
{
urlnow = checkedLocationsArray[i];
if(urlnow == url)
{
return true;
}
//Check there's nothing else in the string
urlnow = '^' + urlnow + '$';
if(urlnow.indexOf('*') != -1)
{
while(urlnow.indexOf("*") != -1)
urlnow = urlnow.replace("\*", ".*");
}
else if(urlnow.lastIndexOf('/') != -1)
{
return false;
}
var regex = new RegExp(urlnow);
var Erg = regex.exec(url);
if(Erg != null)
return true;
}
}
return false;
}
}
}
The problem seems that you don't check for the start and the end of the string. Change your code to something like
urlnow = '^'+urlnow+'$'; // this is new
var regex = new RegExp(urlnow);
^ is the RegExp code for string-start and $ the code for string-end. That way you ensure that the whole url has to match the pattern and not only a part of it.
I figured out that I did the url was not the current url, I changed that below.
I also changed that the * are now replaced with a regular expression and the dots have to be there in this situation.
function redlist_checkURLS(index)
{
if(index >= 0)
{
var pos = getPos("URL-Mask");
var url = currenturl.replace("http://", "");
if(url != null && url != "")
{
var urlnow = "";
if(pref.prefHasUserValue("table.1"))
{
var urlsok = 0;
var checkedLocationsArray = new Array();
for(i = 0; i < tables.length; i++)
{
checkedLocationsArray[i] = tables[i][pos];
}
for(i=0;i<checkedLocationsArray.length;i++)
{
urlnow = checkedLocationsArray[i];
if(urlnow == url)
{
return true;
}
if(urlnow.indexOf('*') != -1)
{
while(urlnow.indexOf("*") != -1)
urlnow = urlnow.replace("*", "\\S+")
}
var regex = new RegExp(urlnow);
var Erg = regex.exec(url);
if(Erg != null && Erg == url)
return true;
}
}
return false;
}
}
}
Thanks for your help thought!

Categories

Resources