Controlling Javascript from server side

A

akineko

Hi everyone,

First of all, I'm not an expert on Javascript. Please forgive me if my
question is pointless.

I want control a hardware device using a Web browser.
I created a page which has a form containing all necessary INPUTs.
By clicking a button, all current settings are sent to the server side
(using POST or GET) so that the server can interact with the hardware,
which is under the server's control.

Now, in some cases, I want to update the INPUT (w/ readonly) with the
data from the hardware, such as a status value.
Most primitive approach is creating a new page with new value to the
INPUT, where I want to show the value.

But that is not quite efficient as the page appearance won't change
except the contents of the INPUT.

As Javascript can make any change to the HTML page (at client's side)
that is currently being displayed, it is more straight forward if the
server can send a set of Javascript commands to the web server so that
it can just update the display contents rather than refreshing
everything.

I thought such scheme was already available, but so far, I don't see
anything usable.
The Web server is not a commercial one but a custom Web server
(written in Python) so that I want to keep the scheme as simple as
possible. I checked AJAX but I'm not sure I can use AJAX in my
application.

Any suggestion will be greatly appreciated.

Best regards,
Aki Niimura
 
D

David Golightly

I thought such scheme was already available, but so far, I don't see
anything usable.
The Web server is not a commercial one but a custom Web server
(written in Python) so that I want to keep the scheme as simple as
possible. I checked AJAX but I'm not sure I can use AJAX in my
application.

Once a page is loaded, you can't push stuff from the server to the
client. The client has to request it first. That's how TCP works.

What you can do, instead, is use JavaScript to poll your server at
regular intervals to check for updates. You would probably end up
using the XMLHttpRequest object (or its equivalent) to check for these
updates.

-David
 
B

Bart Van der Donck

Aki said:
I want control a hardware device using a Web browser.
I created a page which has a form containing all necessary INPUTs.
By clicking a button, all current settings are sent to the server side
(using POST or GET) so that the server can interact with the hardware,
which is under the server's control.

Now, in some cases, I want to update the INPUT (w/ readonly) with the
data from the hardware, such as a status value.
Most primitive approach is creating a new page with new value to the
INPUT, where I want to show the value.

But that is not quite efficient as the page appearance won't change
except the contents of the INPUT.

As Javascript can make any change to the HTML page (at client's side)
that is currently being displayed, it is more straight forward if the
server can send a set of Javascript commands to the web server so that
it can just update the display contents rather than refreshing
everything.

I thought such scheme was already available, but so far, I don't see
anything usable.
The Web server is not a commercial one but a custom Web server
(written in Python) so that I want to keep the scheme as simple as
possible. I checked AJAX but I'm not sure I can use AJAX in my
application.

Ajax is very suitable for this kind of interaction.

A Python programme 'file.py':

#!/usr/bin/env python
print "Content-type: text/html\n\n"
import random
print random.randrange(50)

(for the sake of simplicity, this just reurns a random number 0-50)

A javascript programme:

function ajax(url, vars, callbackFunction) {
if (window.XMLHttpRequest) {
var request = new XMLHttpRequest();
}
else {
var request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
}
request.open('GET', url, true);
request.setRequestHeader('Content-Type', '');
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
if (request.responseText) {
document.getElementById('myField').value =
(request.responseText).replace(/(\r\n|\r|\n|\s)/g, '');
}
}
}
request.send(vars);
// perform new call every 2 seconds (2000 milliseconds)
setTimeout("ajax('file.py?' + Math.random(), '', '')", 2000);
}
document.write('Status value: <input type="text" id="myField">');
ajax('file.py?' + Math.random(), '', '');

I've put a demo on the following URL:

http://www.dotinternet.be/temp/test.htm

Hope this helps,
 
A

akineko

Hi Bart,

Thank you for demonstrating the scheme that uses AJAX.
It is very impressive. It is a good example not only for me but also
for other people who wish to use browser to do more.
With AJAX (Javascript as a fundation), you can do pretty much
anything.

Thanks,
Aki Niimura
 
T

Thomas 'PointedEars' Lahn

Bart said:
Ajax is very suitable for this kind of interaction.

A Python programme 'file.py':

#!/usr/bin/env python
print "Content-type: text/html\n\n"

The "Content-Type" header value of a HTTP message should always contain a
declaration of the encoding of the message body ("charset=...").
import random
print random.randrange(50)

(for the sake of simplicity, this just reurns a random number 0-50)

A javascript programme:

It is merely ECMAScript-3-conforming code, or such a script or program.
It may seem like nitpicking, but it is very important to understand that
whether it is JavaScript or not is defined by the execution environment,
that is the ECMAScript *implementation*, the script engine that is used
to execute the code. For example, it would be Netscape JavaScript in NN2+
and Gecko-based UAs, Microsoft JScript in MSHTML (IE-based), Opera
ECMAScript in Opera, KJS ECMAScript in Konqueror, and JavaScriptCore
JavaScript in Safari. (Hence my use of the terms "J(ava)Script/ECMAScript"
or "JS/ES".)

See also http://PointedEars.de/scripts/es-matrix for differences between
some ECMAScript implementations. (I will add more implementations there;
your input, as always, is welcome).


var _global = this;
function ajax(url, vars, callbackFunction) {
if (window.XMLHttpRequest) {

Wrong feature test. Should be:

if (/\b(function|object)\b/i.test(typeof XMLHttpRequest)
&& _global.XMLHttpRequest)
var request = new XMLHttpRequest();

One wants to attempt exception handling here in the case this fails anyway.
}
else {
var request = new ActiveXObject('MSXML2.XMLHTTP.3.0');

Contrary to what the MSDN Library says, it is not necessary here to force a
specific (the newest) version of MSXML or IXMLHTTPRequest; all used
properties are available ever since. The required exception handling should
be added in the case this fails.
}
request.open('GET', url, true);

AFAIK the third argument is unnecessary here, although may be used to
indicate the default value (`true').

http://msdn2.microsoft.com/en-us/library/ms757849.aspx
http://xulplanet.com/references/objref/XMLHttpRequest.html#method_open
request.setRequestHeader('Content-Type', '');

That would make the HTTP request invalid, as the header name "Content-Type"
is inappropriate at least for a *GET* request. (HTTP/1.x does not define
such a request header for any request type, only a response header.[1]
[CMIIW] However, to submit different types of information on POST requests,
HTML 4.01 specified implicitly that the Content-Type header may be used also
for request messages. The default used for submitting forms with POST is
specified as "application/x-www-form-urlencoded" which usually suffices.[2]
It is not used by the interface for GET; those requests have no Content-Type
header by default.)

And, more important, the header value must not be empty. The interface does
not specify a default value to be used when the second parameter is the
empty string.

That method call in general will also throw an exception with some builds,
IIRC of Opera.

[1] http://www.rfc-editor.org/rfc/rfc1945.txt
http://www.rfc-editor.org/rfc/rfc2616.txt
[2] http://www.w3.org/TR/html401/interact/forms.html#form-content-type
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {

Other final response status codes than `200' are possible for a successful
request, see HTTP/1.x and the interface specification.
if (request.responseText) {

That test would only handle the case (and improve efficiency a bit with the
code below) if the response body would be empty. It can be safely omitted.
document.getElementById('myField').value =

Missing feature test, therefore error-prone referencing.
(request.responseText).replace(/(\r\n|\r|\n|\s)/g, '');

There is no need for parantheses around the object reference, and the
Regular Expression can be written more efficient (matching the same characters):

... = request.responseText.replace(/\s+/g, '');

http://developer.mozilla.org/en/doc...Exp#Special_characters_in_regular_expressions
}
}
}
request.send(vars);

This assumes a POST request where the argument of IXMLHTTPRequest::send()
specifies the message body. However, that is not the case here (it's GET),
so the value should be `undefined' (i.e. not passed at all), or `null' to be
compatible to the Gecko DOM. That decision should not be left to the caller
of ajax().
// perform new call every 2 seconds (2000 milliseconds)
setTimeout("ajax('file.py?' + Math.random(), '', '')", 2000);
}
document.write('Status value: <input type="text" id="myField">');

If a `form' element would be written here that contained the `input'
element, the feature test for D::gEBI() above would be unnecessary.
ajax('file.py?' + Math.random(), '', '');

Given the nature of random numbers in general, and especially
machine-generated random numbers, this will not avoid a cached
resource to be retrieved, which was probably the intention.
The following would:

ajax('file.py?' + (new Date()).getTime(), '', '');


PointedEars
 
B

Bart Van der Donck

Thomas said:
The "Content-Type" header value of a HTTP message should always contain a
declaration of the encoding of the message body ("charset=...").

And in absence of which, the expected encoding is always ISO/IEC
8859-1, being the default HTTP charset ever since. It's not widely
used to set a character set here, unless, of course, you want
something else than ISO/IEC 8859-1. But it's not a bad habit nowadays
to add it anyhow, especially in regard to the growing Unicode support
and further internationalization of the internet.
A javascript programme:
[ snip code ]

It is merely ECMAScript-3-conforming code, or such a script or program.

Then I suggest we rename this group to 'comp.lang.ECMAScript-3-
conforming-code'.
It may seem like nitpicking, but it is very important to understand that
whether it is JavaScript or not is defined by the execution environment,
that is the ECMAScript *implementation*, the script engine that is used
to execute the code. For example, it would be Netscape JavaScript in NN2+
and Gecko-based UAs, Microsoft JScript in MSHTML (IE-based), Opera
ECMAScript in Opera, KJS ECMAScript in Konqueror, and JavaScriptCore
JavaScript in Safari. (Hence my use of the terms "J(ava)Script/ECMAScript"
or "JS/ES".)

I am aware that different browers have different js engines, yes.
var _global = this;


Wrong feature test. Should be:

if (/\b(function|object)\b/i.test(typeof XMLHttpRequest)
&& _global.XMLHttpRequest)

Code for the lab.
One wants to attempt exception handling here in the case this fails anyway.

I haven't seen any advisories that recommend it on this place.
Contrary to what the MSDN Library says, it is not necessary here to force a
specific (the newest) version of MSXML or IXMLHTTPRequest; all used
properties are available ever since. The required exception handling should
be added in the case this fails.

The inner working of MSXML is not accessible, so I follow the
guidelines recommended by Microsoft in their documentation. Seems a
reasonable approach to me.
AFAIK the third argument is unnecessary here, although may be used to
indicate the default value (`true').

'true' means that the request must be handled asynchronously. Makes
sense to me to set it here explicitly for code clarity that we want
async here and not sync (even when 'true' would be the default).
That would make the HTTP request invalid,

No, the request will still be valid.
as the header name "Content-Type" is inappropriate at least for a *GET*
request. (HTTP/1.x does not define such a request header for any request
type, only a response header.[1]

It doesn't matter. If you use a header like...

abc: 123

....it would still remain a valid request. The most you can say, is
that the receiver doesn't do anything with this information. Receiver
might ignore or not understand the line, but that never affects the
(in)validity of the request as a whole. You're correct that a false
impression may be created here (as if the query string were offered as
text/html or something, while it is always one ASCII percent-endoded
string).
[CMIIW] However, to submit different types of information on POST requests,
HTML 4.01 specified implicitly that the Content-Type header may be used also
for request messages. The default used for submitting forms with POST is
specified as "application/x-www-form-urlencoded" which usually suffices.[2]

True, and that's exactly why it can be left empty in my code. No need
It is not used by the interface for GET; those requests have no Content-Type
header by default.)

And, more important, the header value must not be empty. The interface does
not specify a default value to be used when the second parameter is the
empty string.

That method call in general will also throw an exception with some builds,
IIRC of Opera.

[1]http://www.rfc-editor.org/rfc/rfc1945.txt
http://www.rfc-editor.org/rfc/rfc2616.txt
[2]http://www.w3.org/TR/html401/interact/forms.html#form-content-type
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {

Other final response status codes than `200' are possible for a successful
request, see HTTP/1.x and the interface specification.

Depends on what resource is requested. Code 200 will be okay in
default uses of XMLHttpRequest, unless, of course, you want something
else.
That test would only handle the case (and improve efficiency a bit with the
code below) if the response body would be empty. It can be safely omitted.

I suppose it's quite possible that the body of the response would be
empty, like for instance a database that's not reachable. And what
about feature testing ?
Missing feature test, therefore error-prone referencing.

Of course the programmer must create an element with ID 'myField'. Of
course the programmer supposes that 'getElementById' is supported by
the client. Do you really believe that it's necessary to feature-test
on all these elementary things ? I don't.
There is no need for parantheses around the object reference, and the
Regular Expression can be written more efficient (matching the same characters):

... = request.responseText.replace(/\s+/g, '');
Correct.


This assumes a POST request where the argument of IXMLHTTPRequest::send()
specifies the message body. However, that is not the case here (it's GET),
so the value should be `undefined' (i.e. not passed at all), or `null' to be
compatible to the Gecko DOM. That decision should not be left to the caller
of ajax().

'send()' is better when using GET.
If a `form' element would be written here that contained the `input'
element, the feature test for D::gEBI() above would be unnecessary.

Naturally, it's the intention that the original poster will not only
[QUOTE="but makes a total webpage with said:
ajax('file.py?' + Math.random(), '', '');

Given the nature of random numbers in general, and especially
machine-generated random numbers, this will not avoid a cached
resource to be retrieved, which was probably the intention.
The following would:

ajax('file.py?' + (new Date()).getTime(), '', '');[/QUOTE]

That is conceptually better, yes. But any idea about which scale we're
talking here ? Math.random() gives me 15 to 18 digits after comma,
let's say 16 for easy calculation. A user would have 1 chance out of
10.000.000.000.000.000 that the next value is the same. With a 2
second refresh, the scope is 634.195.839 years. The difference is in
the head.
 
T

Thomas 'PointedEars' Lahn

Bart said:
And in absence of which, the expected encoding is always ISO/IEC
8859-1, being the default HTTP charset ever since. It's not widely used
to set a character set here, unless, of course, you want something else
than ISO/IEC 8859-1.

That is specified so in HTTP/1.x. However, it is not implemented this way,
as the HTML 4.01 Specification points out:

http://www.w3.org/TR/html401/charset.html#h-5.2.2
But it's not a bad habit nowadays to add it anyhow, especially in regard
to the growing Unicode support and further internationalization of the internet.

Declaring the character encoding was and still is a requirement for
interoperability.
A javascript programme:
[ snip code ]
It is merely ECMAScript-3-conforming code, or such a script or program.

Then I suggest we rename this group to 'comp.lang.ECMAScript-3-
conforming-code'. [...]

I am not particularly inclined to support that. While it is similar to the
correct name, ECMAScript implementations are *commonly* known as
"JavaScript". And it follows from Usenet practice that the name of a
newsgroup is not always the best or correct one; technical innovation
introduce new techniques that can be summarized under a common name because
of their similarities. Netscape JavaScript was the first implementation,
and the newsgroup has the greatest chance to be found under that name.

That does not mean it should not be pointed out to the people who actually
subscribe to this newsgroup that we are not dealing with one language named
JavaScript, but (at least) five different language implementations here.
The FAQ mentions it partly, and should emphasize it more.
I am aware that different browers have different js engines, yes.

That section was of course not only for you; at least I hoped that what was
written would not be completely new to you. But we are talking not only
browsers, not even only Web user agents. (Did I mention Macromedia/Adobe
ActionScript and Adobe PDF ECMAScript?)
Code for the lab.

No. Before you call something, you should be pretty sure that it can be
called; especially when you use it as a constructor for an object. It will
cause a runtime error and will make you look incompetent otherwise.
I haven't seen any advisories that recommend it on this place.

Which does not mean that it should not be done. With host objects, all bets
are off *by definition* (ECMAScript Ed. 3, subsection 8.6.2).
The inner working of MSXML is not accessible, so I follow the
guidelines recommended by Microsoft in their documentation. Seems a
reasonable approach to me.

"Microsoft.XMLHTTP" should suffice and select the most recent installed version.
'true' means that the request must be handled asynchronously. Makes
sense to me to set it here explicitly for code clarity that we want
async here and not sync (even when 'true' would be the default).

JFTR: `true' *is* the default.
No, the request will still be valid.

It will not. *Generally* the header value is optional:

,-<http://www.rfc-editor.org/rfc/rfc1945.txt>, 4.2
|
| HTTP-header = field-name ":" [ field-value ] CRLF

However, the "Content-Type" header is explicitly defined as:

,-<http://www.rfc-editor.org/rfc/rfc1945.txt>, 10.5 and 3.6
|
| media-type = type "/" subtype *( ";" parameter )
| type = token
| subtype = token
| [...]
| Content-Type = "Content-Type" ":" media-type
as the header name "Content-Type" is inappropriate at least for a *GET*
request. (HTTP/1.x does not define such a request header for any request
type, only a response header.[1]

It doesn't matter.

It matters here.
If you use a header like...

abc: 123

...it would still remain a valid request.

True, because of

,-<http://www.rfc-editor.org/rfc/rfc1945.txt>, 4.3
|
| Unrecognized header fields are treated as Entity-Header fields.

,-<http://www.rfc-editor.org/rfc/rfc1945.txt>, 7.1
|
| Entity-Header = Allow ; Section 10.1
| | Content-Encoding ; Section 10.3
| | Content-Length ; Section 10.4
| | Content-Type ; Section 10.5
| | Expires ; Section 10.7
| | Last-Modified ; Section 10.10
| | extension-header
|
| extension-header = HTTP-header

However:

| The extension-header mechanism allows additional Entity-Header fields
| to be defined without changing the protocol, but these fields cannot
| be assumed to be recognizable by the recipient. Unrecognized header
| fields should be ignored by the recipient and forwarded by proxies.

One should not disregard standards unless one has a very good reason
to do so. There is exactly *no* reason for such a thing here.
[CMIIW] However, to submit different types of information on POST requests,
HTML 4.01 specified implicitly that the Content-Type header may be used also
for request messages. The default used for submitting forms with POST is
specified as "application/x-www-form-urlencoded" which usually suffices.[2]

True, and that's exactly why it can be left empty in my code. No need
to write every <form> as <form enctype="application/x-www-form-
urlencoded"> neither.

You send a "Content-Type" header that has an empty value. That is
fundamentally different from sending no "Content-Type" header at all,
or sending it with the default value as specified in HTML 4.01.
I suppose it's quite possible that the body of the response would be
empty, like for instance a database that's not reachable.

However, an error status code is then indicated instead.
And what about feature testing ?

Not necessary here. When readyState == 4, responseText has to exist or the
implementation is FUBAR.
Of course the programmer must create an element with ID 'myField'. Of
course the programmer supposes that 'getElementById' is supported by
the client. Do you really believe that it's necessary to feature-test
on all these elementary things ? I don't.

I do. Because it always breaks with the client, not in the test cases.
'send()' is better when using GET.

-v please
Naturally, it's the intention that the original poster will not only
use <input>, but makes a total webpage with <form>, <html>, <body>
etc.

Should then not the most compatible solution be presented in the first place?
That is conceptually better, yes. But any idea about which scale we're
talking here ?

Well, *I* do.
Math.random() gives me 15 to 18 digits after comma,

However, that is only the string representation of the IEEE-754 double;
the actual precision is much greater than that.
let's say 16 for easy calculation. A user would have 1 chance out of
10.000.000.000.000.000 that the next value is the same. With a 2
second refresh, the scope is 634.195.839 years. The difference is in
the head.

Different numeric values can have the same string representation, so the
chances are much greater than you think.

But that does not really matter:

From the Law of Probability follows that any event E that can be the outcome
of a Random Experiment (i.e. P(E) > 0) may occur again the next time the
Random Experiment is performed, no matter how great the statistical
probability for that event is. It is foolish to ignore that. Especially
as we are dealing with machine-generated random numbers here, which only
implement pseudo-randomness.


PointedEars
 
B

Bart Van der Donck

Thomas said:
That is specified so in HTTP/1.x.

Then it proves my argument Ita Scripta Est.
However, it is not implemented this way, as the HTML 4.01 Specification
points out: http://www.w3.org/TR/html401/charset.html#h-5.2.2


Declaring the character encoding was and still is a requirement for
interoperability.

http://www.w3.org/TR/html401/conform.html#h-4.3 clearly states that
charset is an *optional* parameter, how recommended it may be.
A javascript programme:
[ snip code ]
It is merely ECMAScript-3-conforming code, or such a script or program.
Then I suggest we rename this group to 'comp.lang.ECMAScript-3-
conforming-code'. [...]

I am not particularly inclined to support that.

Me neither. Come on. It was a joke.
While it is similar to the
correct name, ECMAScript implementations are *commonly* known as
"JavaScript". And it follows from Usenet practice that the name of a
newsgroup is not always the best or correct one; technical innovation
introduce new techniques that can be summarized under a common name because
of their similarities. Netscape JavaScript was the first implementation,
and the newsgroup has the greatest chance to be found under that name.

That does not mean it should not be pointed out to the people who actually
subscribe to this newsgroup that we are not dealing with one language named
JavaScript, but (at least) five different language implementations here.
The FAQ mentions it partly, and should emphasize it more.

The language is called javascript and browsers build their own
javascript engines. Many high-level languages work with different
compilers or may have environmental differences; but that doesn't mean
that the language isn't the same.
No. Before you call something, you should be pretty sure that it can be
called; especially when you use it as a constructor for an object. It will
cause a runtime error and will make you look incompetent otherwise.

"if (window.XMLHttpRequest) { ..." is so widely used that I cannot
imagine this would ever be problematic. To be fair, I never saw
something else.
var request = new ActiveXObject('MSXML2.XMLHTTP.3.0');

"Microsoft.XMLHTTP" should suffice and select the most recent installed version.

Okay - it doesn't matter much, right ? I follow MSDN and say
'MSXML2.XMLHTTP.3.0', you say 'Microsoft.XMLHTTP' and that will
probably work too.
JFTR: `true' *is* the default.

I didn't say it wasn't. My argument was that the code becomes clearer
when 'true' is explicitly mentionned, as to indicate that the request
must be done asynchronously.

There is often an important gap in your arguments and this
demonstrates it clearly.

WHEN 'true' is the default,
AND people must *know* that 'true' is the default (which is far from
guaranteed),
AND it does not matter if it says 'true' or not,
THEN it is better to mention 'true' on that place.

It's not technical argument but an educational one, which certainly
stands on the same height.
It will not.

Let's see. Can you name *one* browser or server where my request would
be invalid ? (thus, generating an error ?)
True, because of

,-<http://www.rfc-editor.org/rfc/rfc1945.txt>, 4.3
|
| Unrecognized header fields are treated as Entity-Header fields.

,-<http://www.rfc-editor.org/rfc/rfc1945.txt>, 7.1
|
| Entity-Header = Allow ; Section 10.1
| | Content-Encoding ; Section 10.3
| | Content-Length ; Section 10.4
| | Content-Type ; Section 10.5
| | Expires ; Section 10.7
| | Last-Modified ; Section 10.10
| | extension-header
|
| extension-header = HTTP-header

However:

| The extension-header mechanism allows additional Entity-Header fields
| to be defined without changing the protocol, but these fields cannot
| be assumed to be recognizable by the recipient. Unrecognized header
| fields should be ignored by the recipient and forwarded by proxies.

One should not disregard standards unless one has a very good reason
to do so. There is exactly *no* reason for such a thing here.

Indeed there is no reason, as it may create a wrong impression for the
reader of the code. You snipped my part where I said:

| You're correct that a false impression may be created here (as if
the query
| string were offered as text/html or something, while it is always
one ASCII
| percent-endoded string).
You send a "Content-Type" header that has an empty value. That is
fundamentally different from sending no "Content-Type" header at all,
or sending it with the default value as specified in HTML 4.01.

Correct. It should not be specified.
However, an error status code is then indicated instead.

Not necessarily. A response might be perfectly desired and valid as
being empty.
Not necessary here. When readyState == 4, responseText has to exist or the
implementation is FUBAR.

So you say that feature testing is necessary for:

document.getElementById('myField')

but obsolete for:

if (request.responseText) {

Very odd.
I do. Because it always breaks with the client, not in the test cases.

So I suppose you advocate constructions like

if (window.alert) { window.alert('xx') }

That is *Miles* away from Praxis.
Should then not the most compatible solution be presented in the first place?

I presented basic code that demonstrated the working in a reasonable
way. Of course I should not have presented a "compatible solution" as
you seem to call it. Look at the OP's reaction. He quickly understands
the code, what it does, how it works, what it means and he has
something workable in his hands.
However, that is only the string representation of the IEEE-754 double;
the actual precision is much greater than that.


Different numeric values can have the same string representation, so the
chances are much greater than you think.

I was not talking about the values that are generated by
Math.random(), but about the sent URL's. These follow the
*representation* of the string and are not necessarily the same as the
result of the actual Math.random() call.
But that does not really matter:

From the Law of Probability follows that any event E that can be the outcome
of a Random Experiment (i.e. P(E) > 0) may occur again the next time the
Random Experiment is performed, no matter how great the statistical
probability for for that event is. It is foolish to ignore that.

Statistically correct. I just wanted to demonstrate the rough scale.
The chance exists, but is negligible in practice here.
 
T

Thomas 'PointedEars' Lahn

Randy said:
Bart Van der Donck said the following on 8/29/2007 7:20 PM:
Thomas said:
Bart Van der Donck wrote:
Thomas 'PointedEars' Lahn wrote:
A javascript programme:
[ snip code ]
It is merely ECMAScript-3-conforming code, or such a script or program.
Then I suggest we rename this group to 'comp.lang.ECMAScript-3-
conforming-code'. [...]
I am not particularly inclined to support that.
Me neither. Come on. It was a joke.

I see Thomas has changed his mind.


Not really. If you read what you snipped, I explain why I think it is a bad
idea to rename the newsgroup. The reasoning is the same (the group would
hardly be found even though the name would be better), the explanation this
time is just more verbose. You will also observe that the suggestion was
different this time (the previous one was more reasonable; and yes, I got
Bart's joke right away), hence a different reaction.

I also wonder why you find it necessary to state that you *think* you have
seen me change my mind. (If you follow my postings more closely, you will
observe that this happens often if I am presented with valid reasons to do so.)


HTH & HAND

PointedEars
 
A

akineko

David said:
Thomas 'PointedEars' Lahn wrote:
Bart Van der Donck wrote:
Randy Webb wrote:

I would like to thank all of you guys to respond to my posting (more
than I hoped).
I really thank Bart for creating a test script and demonstrating that
it is feasible.

Probably this is not new for you guys here but what Bart has
demonstrated is un-tapped potentials.
Outside this group, actually I'm a hardware guy rather than a software
guy, not many people realizes such capabilities the browser can
unleash.

I will review the posting and I will incorporate the idea here to my
application.

Aki-
 
T

Thomas 'PointedEars' Lahn

Bart said:
Then it proves my argument Ita Scripta Est.

No, it does not, as the specification and the implementations differ here.
http://www.w3.org/TR/html401/conform.html#h-4.3 clearly states that
charset is an *optional* parameter, how recommended it may be.

| The optional parameter "charset" refers to the character encoding used to
| represent the HTML document as a sequence of bytes. Legal values for this
| parameter are defined in the section on character encodings. Although this
| parameter is optional, we recommend that it always be present.

The reasoning for this recommendation is given in the section I have pointed
to. To ignore that recommendation is foolish, as we are talking about a Web
standard.
A javascript programme:
[ snip code ]
It is merely ECMAScript-3-conforming code, or such a script or program.
Then I suggest we rename this group to 'comp.lang.ECMAScript-3-
conforming-code'. [...]
I am not particularly inclined to support that.

Me neither. Come on. It was a joke.

You irony detector is borken.
The language is called javascript and browsers build their own
javascript engines. Many high-level languages work with different
compilers or may have environmental differences; but that doesn't mean
that the language isn't the same.

So you do *not* understand. There are not different "javascript engines",
there are different ECMAScript implementations. And that, again, is a
fundamental difference.
"if (window.XMLHttpRequest) { ..." is so widely used that I cannot
imagine this would ever be problematic. To be fair, I never saw
something else.

Assuming that there even is *window*.XMLHttpRequest is the first mistake.

Calling it without testing that it can be called is the next one.

Using it as a constructor without handling the case that this throws an
exception is the third one.

Early implementations of IXMLHTTPRequest in some environments (such as
Opera 8.0) provided the object, but did not provide it fully functional.
New implementations might also do that.

If your application is ever exposed to such an execution environment, it
will break; either silently in the background with nobody noticing it or
loud and clear as a nice big error message. Either way, the user will not
be able to interpret that in another way as "bad code".

Do I have to assume that you are going to blame the user for this?
Okay - it doesn't matter much, right ? I follow MSDN and say
'MSXML2.XMLHTTP.3.0',

Where the code will break because of the required COM/ActiveX object version
to be not installed, without the additional features of the newer version
being required here.
you say 'Microsoft.XMLHTTP'

I said that for a good reason.
and that will probably work too.

"Will probably work" is an expression of a Voodoo programmer. A reasonable
programmer would state "This code cannot possibly fail, because ...", and
rightly so.
I didn't say it wasn't. My argument was that the code becomes clearer
when 'true' is explicitly mentionned, as to indicate that the request
must be done asynchronously.

There is often an important gap in your arguments and this
demonstrates it clearly.

I seriously doubt that.
WHEN 'true' is the default,
AND people must *know* that 'true' is the default (which is far from
guaranteed),
AND it does not matter if it says 'true' or not,
THEN it is better to mention 'true' on that place.

It's not technical argument but an educational one, which certainly
stands on the same height.

You, the author of the code, now know that it is. Anyone interested in your
code will have to look up the meaning of the third argument anyway if they
are to understand what it does. I don't see the difference.
Let's see. Can you name *one* browser or server where my request would
be invalid ? (thus, generating an error ?)

I am talking mostly servers, not user agents. However, you are trying to
shift the burden of proof; a common fallacy.
Indeed there is no reason, as it may create a wrong impression for the
reader of the code. You snipped my part where I said:

| You're correct that a false impression may be created here (as if
| the query string were offered as text/html or something, while it
| is always one ASCII percent-endoded string).

No, you are mixing up the cases here. With *any* non-standard header, you
are correct, and the above applies. However, with *your* _Content-Type_
header, the HTTP message clearly is invalid as the grammar of HTTP is not
followed.
Not necessarily. A response might be perfectly desired and valid as
being empty.

You have been arguing that a database access error would be a valid reason
and now you are trying to wind out of that.
So you say that feature testing is necessary for:

document.getElementById('myField')

but obsolete for:

if (request.responseText) {

Very odd.

That is not odd at all. `document.getElementById()' is not backwards
compatible; `document' is. `request' is not backwards-compatible, and
neither is `request.responseText'; however, in contrast to document,
`request' is an implementation of a well-defined interface; it is
specified that request.responseText exists when readyState == 4.
BTW: The above would not qualify as a feature test anyway.
So I suppose you advocate constructions like

if (window.alert) { window.alert('xx') }

That is *Miles* away from Praxis.

Fallacy #2: Drawing conclusions from supposed opinions.
I presented basic code that demonstrated the working in a reasonable
way. Of course I should not have presented a "compatible solution" as
you seem to call it.

Yes, you should have, as that would have been presenting best common
practice, something of *real* value.
Look at the OP's reaction.
YMMD.

He quickly understands the code, what it does, how it works, what it
means and he has something workable in his hands.

He merely *thinks* he understands it because you did not explain the
pitfalls of your solution.
I was not talking about the values that are generated by
Math.random(), but about the sent URL's. These follow the
*representation* of the string and are not necessarily the
same as the result of the actual Math.random() call.

Which is the error in your reasoning.

"0.7546356374078109"

is the string representation of

0.7546356374078108665...
0.754635637407810867...
0.75463563740781087...
0.75463563740781088...
0.75463563740781089...
0.75463563740781090...
0.75463563740781091...
0.75463563740781092...
0.75463563740781093...
0.75463563740781094...
0.75463563740781095...
0.75463563740781096...
and
0.75463563740781097...

Of course I missed some, but that does not really matter.

BTW:
The precision of an IEEE-754 double-precision floating-point number is 64 bits.
Statistically correct. I just wanted to demonstrate the rough scale.
The chance exists, but is negligible in practice here.

You are not only a fool who does not understand what he is doing, but also
an ignorant who ignores the correct explanation for his wrong-doing when he
is provided with it.


PointedEars
 
B

Bart Van der Donck

Time for some conclusions in this thread.

- The use of a charset is not required by HTTP specifications, but it
is recommended.
- A javascript engine is a implementation of (a version of) an
ECMAScript specification.
- You were not able to proof any of your positions in a real-world
environment. You did perform a few interesting tests in the lab
though.
- Don't code, discuss or feature-detect Ex Absurdum.
- Using date() is recommended for randomizing URIs. Math.random() may
be used as well under "common sense" conditions.
- The original poster received a working, practical, cross-browser and
suitable answer to his question.
- There are more than sheer technical arguments, and they're often
more important.
- Use the right Content-Type.
- There is a difference between theory and practice.
- Type a smiley when telling a joke.
 
B

Bart Van der Donck

Bart said:
Time for some conclusions in this thread.
[...]

The academic world evaluates software using these criteria:
- maintainable
- adaptable
- transparent
- user-friendly
- reliable
- efficient

In short the 'MATURE'-concept, which is widely accepted to evaluate
when software has outgrown its juvenile stage.

You're young and technically brilliant. But your fundamental
misconception (in all your posts) is that you lift up the reliability/
efficiency criteria to an absurd level. The other 4 criteria suffer
heavily from that. This attitude is dangerous and not suitable to
achieve quality software.
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]
oglegroups.com>, Wed, 29 Aug 2007 12:13:37, Bart Van der Donck
That is conceptually better, yes. But any idea about which scale we're
talking here ? Math.random() gives me 15 to 18 digits after comma,
let's say 16 for easy calculation.

In that case, it probably gives about 2^53 different values. However,
Opera 9.21 & 9.23 give only about 2^31 values, or so it seems.

In cases where each state of the PRNG gives a different value to
Math.random(), the latter will NOT repeat until all states have been
traversed.
 
T

The Natural Philosopher

Bart said:
Bart said:
Time for some conclusions in this thread.
[...]

The academic world evaluates software using these criteria:
- maintainable
- adaptable
- transparent
- user-friendly
- reliable
- efficient

In short the 'MATURE'-concept, which is widely accepted to evaluate
when software has outgrown its juvenile stage.

You're young and technically brilliant. But your fundamental
misconception (in all your posts) is that you lift up the reliability/
efficiency criteria to an absurd level. The other 4 criteria suffer
heavily from that. This attitude is dangerous and not suitable to
achieve quality software.

All software is a bloody compromise between all of those.
Now and again some academic writes a learned paper about how to achieve
one or other of them absolutely, but never mentions the disastrous
effect it has on some or all of the others.

I could cite example after example.
 
B

Bart Van der Donck

Dr said:
In comp.lang.javascript message <[email protected]
oglegroups.com>, Wed, 29 Aug 2007 12:13:37, Bart Van der Donck



In that case, it probably gives about 2^53 different values. However,
Opera 9.21 & 9.23 give only about 2^31 values, or so it seems.

In cases where each state of the PRNG gives a different value to
Math.random(), the latter will NOT repeat until all states have been
traversed.

I was not aware of that, and find it surprising. I sofar I remember my
math classes, a true randomizer should be like Thomas said, namely,
although a chance is statistically extremely unlikely, it can never be
excluded (cfr. "It's possible to win the lottery every week").

I think date() is conceptually better here.
 
B

Bart Van der Donck

The said:
All software is a bloody compromise between all of those.
Now and again some academic writes a learned paper about how to achieve
one or other of them absolutely, but never mentions the disastrous
effect it has on some or all of the others.

I couldn't agree more.
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]
oglegroups.com>, Fri, 31 Aug 2007 01:16:40, Bart Van der Donck
Dr J R Stockton wrote:

I was not aware of that, and find it surprising.

It is an inevitable property of any digital pseudo-random number
generator in which the next output and the next internal state are
entirely determined by the internal state.

For those writing ECMA/ISO/IEC standard version 4 or 5 : it is a defect
of Javascript that the internal state of the PRNG is not read/write
accessible. If accessible, it would be possible for testing to generate
the same set of random numbers as often as desired.

<URL:http://www.merlyn.demon.co.uk/js-randm.htm> shows the basics of a
reproducible PRNG method in Javascript, using a 32-bit seed and a known-
good constant. Conversion to 48-bit seed requires a good constant to be
found (Knuth?). Conversion to more than 52 or 53 bits would need real
work, but a good constant is available.

It's a good idea to update the newsgroup c.l.j and its FAQ. See below.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top