Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.javascript > #28773 > unrolled thread
| Started by | JiiPee <no@notvalid.com> |
|---|---|
| First post | 2015-10-02 00:13 +0100 |
| Last post | 2015-10-02 20:29 +0200 |
| Articles | 20 on this page of 33 — 7 participants |
Back to article view | Back to comp.lang.javascript
How to pass a php variable to a javascript file (function)? JiiPee <no@notvalid.com> - 2015-10-02 00:13 +0100
Re: How to pass a php variable to a javascript file (function)? "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2015-10-02 09:44 +0200
Re: How to pass a php variable to a javascript file (function)? Stefan Weiss <krewecherl@gmail.com> - 2015-10-02 12:14 +0200
Re: How to pass a php variable to a javascript file (function)? JiiPee <no@notvalid.com> - 2015-10-02 11:43 +0100
Re: How to pass a php variable to a javascript file (function)? JiiPee <no@notvalid.com> - 2015-10-02 11:58 +0100
Re: How to pass a php variable to a javascript file (function)? Stefan Weiss <krewecherl@gmail.com> - 2015-10-02 13:38 +0200
Re: How to pass a php variable to a javascript file (function)? JiiPee <no@notvalid.com> - 2015-10-02 12:53 +0100
Re: How to pass a php variable to a javascript file (function)? JiiPee <no@notvalid.com> - 2015-10-02 13:46 +0100
Re: How to pass a php variable to a javascript file (function)? Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-10-02 13:51 +0100
Re: How to pass a php variable to a javascript file (function)? Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2015-10-02 21:42 +0200
Re: How to pass a php variable to a javascript file (function)? Stefan Weiss <krewecherl@gmail.com> - 2015-10-03 00:33 +0200
Re: How to pass a php variable to a javascript file (function)? JiiPee <no@notvalid.com> - 2015-10-02 23:45 +0100
Re: How to pass a php variable to a javascript file (function)? Tim Streater <timstreater@greenbee.net> - 2015-10-02 23:55 +0100
Re: How to pass a php variable to a javascript file (function)? JiiPee <no@notvalid.com> - 2015-10-03 00:02 +0100
Re: How to pass a php variable to a javascript file (function)? JiiPee <no@notvalid.com> - 2015-10-02 23:49 +0100
Re: How to pass a php variable to a javascript file (function)? Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2015-10-02 21:37 +0200
Re: How to pass a php variable to a javascript file (function)? Stefan Weiss <krewecherl@gmail.com> - 2015-10-03 00:34 +0200
Re: How to pass a php variable to a javascript file (function)? Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2015-10-03 04:35 +0200
Re: How to pass a php variable to a javascript file (function)? Stefan Weiss <krewecherl@gmail.com> - 2015-10-05 01:11 +0200
Re: How to pass a php variable to a javascript file (function)? Tim Streater <timstreater@greenbee.net> - 2015-10-05 09:13 +0100
Re: How to pass a php variable to a javascript file (function)? Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2015-10-06 03:30 +0200
Re: How to pass a php variable to a javascript file (function)? Stefan Weiss <krewecherl@gmail.com> - 2015-10-10 00:27 +0200
Re: How to pass a php variable to a javascript file (function)? Joao Rodrigues <groups_jr-1@yahoo.com.br> - 2015-10-03 15:15 -0300
Re: How to pass a php variable to a javascript file (function)? Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2015-10-03 20:34 +0200
Re: How to pass a php variable to a javascript file (function)? Joao Rodrigues <groups_jr-1@yahoo.com.br> - 2015-10-03 15:59 -0300
Re: How to pass a php variable to a javascript file (function)? Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2015-10-03 22:15 +0200
Re: How to pass a php variable to a javascript file (function)? JiiPee <no@notvalid.com> - 2015-10-02 11:36 +0100
Re: How to pass a php variable to a javascript file (function)? "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2015-10-02 16:34 +0200
Re: How to pass a php variable to a javascript file (function)? JiiPee <no@notvalid.com> - 2015-10-02 16:00 +0100
Re: How to pass a php variable to a javascript file (function)? Tim Streater <timstreater@greenbee.net> - 2015-10-02 16:03 +0100
Re: How to pass a php variable to a javascript file (function)? JiiPee <no@notvalid.com> - 2015-10-02 17:08 +0100
solution, thanks, seems like one suggestion lead to a solution JiiPee <no@notvalid.com> - 2015-10-02 17:07 +0100
Re: solution, thanks, seems like one suggestion lead to a solution "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2015-10-02 20:29 +0200
Page 1 of 2 [1] 2 Next page →
| From | JiiPee <no@notvalid.com> |
|---|---|
| Date | 2015-10-02 00:13 +0100 |
| Subject | How to pass a php variable to a javascript file (function)? |
| Message-ID | <r6jPx.32747$nl4.14152@fx02.am4> |
I have a php-file which contains a javascript:
<script type="text/javascript">
function doIt() {
var some_string = <?php echo json_encode($sometext); ?>;
window.location.href = encodeURI("index.html");
}
</script>
So it opens a new html site. Then this html site calls javascript
function from a js-file:
test.js :
function doSomething() {
// here I want to use that some_string created in the php file....
}
So in doSomething I want to be able to use this some_string created in
php file. How can I do it? I tried couple of things, but I do not really
understand Ajax... so if the solution is Ajax I would need detailed
information. I checked on the internet but no Ajax example was detailed
enough for me to get it working. Or if there is non-Ajax way that is
also ok.
Or can I pass that some_string first to that html and then that html can
pass it to js-file (to doSomething function)?
But please with Ajax it would need to be detailed answer as I am a
newbie :). All google-Ajax examples failed when I tried them.
Thank you.
[toc] | [next] | [standalone]
| From | "Evertjan." <exxjxw.hannivoort@inter.nl.net> |
|---|---|
| Date | 2015-10-02 09:44 +0200 |
| Message-ID | <XnsA5276328DD4DEeejj99@194.109.6.166> |
| In reply to | #28773 |
JiiPee <no@notvalid.com> wrote on 02 Oct 2015 in comp.lang.javascript:
> I have a php-file which contains a javascript:
Impossible.
Javascript is a language [though some even doubt that].
Perhaps your text-file contains "Javascript script"-text.
> <script type="text/javascript">
> function doIt() {
This does not work, as doIt() is not called clientside.
> var some_string = <?php echo json_encode($sometext); ?>;
This is totally errorprone, you need to enclose the litteral string in '-s
or "-s, ensuring that the ones used do not appear in the inner text.
Have a look houw the resulting stream looks on the client-browser using
view-source.
> window.location.href = encodeURI("index.html");
There is no need to encodeURI() "index.html"'
If[!] doIt() is run then the clientside variable some_string is lost.
> }
> </script>
>
> So it opens a new html site.
No.
If[!] doIt() is run then the browser opens "index.html",
which is not a SITE but a PAGE,
from your server on the browser.
> Then this html site calls javascript
> function from a js-file:
No.
html-PAGES do not CALL javascript files,
they could include code to include a js-file.
> test.js :
>
> function doSomething() {
> // here I want to use that some_string created in the php file....
>}
That variable some_string, being a clientside javascript varaiable on
another PAGE, was lost when leaving that page.
> So in doSomething I want to be able to use this some_string created in
> php file. How can I do it?
So you cannot.
Why don't you create that string on the "index.html" PAGE,
that you probably will have to rename to "index.php".
I tried couple of things, but I do not really
> understand Ajax...
There is no mention of Ajax here, only of some lost serverside json-code.
> so if the solution is Ajax I would need detailed
> information. I checked on the internet but no Ajax example was detailed
> enough for me to get it working. Or if there is non-Ajax way that is
> also ok.
Seems now I am lost, wouldn't it be better if you told us what you really
want to achieve, instead of letting us guess by showing some unworkable
ideas?
> Or can I pass that some_string first to that html and then that html can
> pass it to js-file (to doSomething function)?
Eh?
> But please with Ajax it would need to be detailed answer as I am a
> newbie :). All google-Ajax examples failed when I tried them.
:) ?
Being a newbie is no joke, it is and should be hard.
Seems to me you need to explain what you want in a better way.
Programming primarily is about describing what you want to yourself in a
logical way, not copying code from the web you do not understand and
expecting it to do what you have not visualized.
And remember, only Javascript is on topic here, either clientside or
serverside, php is not.
> Re: How to pass a php variable to a javascript file (function)?
Seems you were talking about a clientside Javascript variable here,
those variables are only valid as long as the PAGE exists,
they do not exist on the [serverside] SITE.
Your "javascript file" surely exists on the server, so including something
there needs serverside scripting. You could howeve include something in the
stream that is sent to the client using php when renaming the js file to:
"myJSfile.js.php".
[Then again, probably you want something else than you say you want.]
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
[toc] | [prev] | [next] | [standalone]
| From | Stefan Weiss <krewecherl@gmail.com> |
|---|---|
| Date | 2015-10-02 12:14 +0200 |
| Message-ID | <mulldu$lli$1@news.albasani.net> |
| In reply to | #28775 |
On 2015-10-02 09:44, Evertjan. wrote: > >> var some_string = <?php echo json_encode($sometext); ?>; > > This is totally errorprone, you need to enclose the litteral string in '-s > or "-s, ensuring that the ones used do not appear in the inner text. No, json_encode() already takes care of quoting and character escaping; adding extra quotes around the result would be a syntax error. That doesn't mean that json_encode() by itself is enough to safely escape strings as JavaScript literals. What if $sometext contains "</script>"? What actually has to be escaped - in addition to characters like quotes, newlines, etc - depends on which HTML version is used. For HTML5, the process and some pitfalls are described here: http://www.w3.org/TR/html5/scripting-1.html#restrictions-for-contents-of-script-elements Short version: | Note: The easiest and safest way to avoid the rather strange | restrictions described in this section is to always escape "<!--" as | "<\!--", "<script" as "<\script", and "</script" as "<\/script" […] > That variable some_string, being a clientside javascript varaiable on > another PAGE, was lost when leaving that page. > >> So in doSomething I want to be able to use this some_string created in >> php file. How can I do it? > > So you cannot. > > Why don't you create that string on the "index.html" PAGE, > that you probably will have to rename to "index.php". Thats one way to do it. Unfortunately, we don't know enough about OP's project to give any meaningful advice. For example, if we knew that `some_string` is relatively short, we could suggest passing it along to index.html in the query string. location.href = "index.html?s=" + encodeURIComponent(some_string); The script included from index.html could then read it back from the query string. In general, mixing dynamic and static files (PHP and plain HTML) like this tends to get messy. - stefan
[toc] | [prev] | [next] | [standalone]
| From | JiiPee <no@notvalid.com> |
|---|---|
| Date | 2015-10-02 11:43 +0100 |
| Message-ID | <fdtPx.34361$uR7.32465@fx18.am4> |
| In reply to | #28777 |
On 02/10/2015 11:14, Stefan Weiss wrote: > On 2015-10-02 09:44, Evertjan. wrote: >>> var some_string = <?php echo json_encode($sometext); ?>; >> This is totally errorprone, you need to enclose the litteral string in '-s >> or "-s, ensuring that the ones used do not appear in the inner text. > No, json_encode() already takes care of quoting and character escaping; > adding extra quotes around the result would be a syntax error. > > That doesn't mean that json_encode() by itself is enough to safely > escape strings as JavaScript literals. What if $sometext contains > "</script>"? > > What actually has to be escaped - in addition to characters like quotes, > newlines, etc - depends on which HTML version is used. > For HTML5, the process and some pitfalls are described here: > http://www.w3.org/TR/html5/scripting-1.html#restrictions-for-contents-of-script-elements > > Short version: > > | Note: The easiest and safest way to avoid the rather strange > | restrictions described in this section is to always escape "<!--" as > | "<\!--", "<script" as "<\script", and "</script" as "<\/script" […] > >> That variable some_string, being a clientside javascript varaiable on >> another PAGE, was lost when leaving that page. >> >>> So in doSomething I want to be able to use this some_string created in >>> php file. How can I do it? >> So you cannot. >> >> Why don't you create that string on the "index.html" PAGE, >> that you probably will have to rename to "index.php". > Thats one way to do it. Unfortunately, we don't know enough about OP's > project to give any meaningful advice. For example, if we knew that > `some_string` is relatively short, we could suggest passing it along to > index.html in the query string. yes. well... this string is actually possible quite long as it is a (random) text from a document. maybe passing like this is not good... as its a bit long > > location.href = "index.html?s=" + encodeURIComponent(some_string); > > The script included from index.html could then read it back from the > query string. yes that is an idea. And then index.html could send it to the js-function it "calls"? maybe better to change html to php first. > > In general, mixing dynamic and static files (PHP and plain HTML) like > this tends to get messy. > > > - stefan
[toc] | [prev] | [next] | [standalone]
| From | JiiPee <no@notvalid.com> |
|---|---|
| Date | 2015-10-02 11:58 +0100 |
| Message-ID | <irtPx.39230$Sf7.19474@fx21.am4> |
| In reply to | #28777 |
I guess my main question is that if I have a php file how can I send data/string from there to a javascript file. php file: contains some data/string test.js file: wants to get hold of that string created in php file
[toc] | [prev] | [next] | [standalone]
| From | Stefan Weiss <krewecherl@gmail.com> |
|---|---|
| Date | 2015-10-02 13:38 +0200 |
| Message-ID | <mulqbe$uvh$1@news.albasani.net> |
| In reply to | #28780 |
On 2015-10-02 12:58, JiiPee wrote: > I guess my main question is that if I have a php file how can I send > data/string from there to a javascript file. > > php file: > contains some data/string > > test.js file: > wants to get hold of that string created in php file Ah. Now that the navigation is out of the way, it's simple enough. test.js has access to the same variables as any inline script in the document. You can make some_string a global variable; local variables in functions are never visible outside the function. - stefan
[toc] | [prev] | [next] | [standalone]
| From | JiiPee <no@notvalid.com> |
|---|---|
| Date | 2015-10-02 12:53 +0100 |
| Message-ID | <xeuPx.30341$xq6.6163@fx14.am4> |
| In reply to | #28781 |
On 02/10/2015 12:38, Stefan Weiss wrote:
> On 2015-10-02 12:58, JiiPee wrote:
>> I guess my main question is that if I have a php file how can I send
>> data/string from there to a javascript file.
>>
>> php file:
>> contains some data/string
>>
>> test.js file:
>> wants to get hold of that string created in php file
> Ah. Now that the navigation is out of the way, it's simple enough.
> test.js has access to the same variables as any inline script in the
> document. You can make some_string a global variable; local variables in
> functions are never visible outside the function.
>
>
ok, am currently testing this. But my code in php is not even able to
call javascript function (in an external file). What am i doing wrong:
php file:
------------
<script type="text/javascript" src="test.js"></script>
...// some button triggers callExternalJSFunction()
<script>...
function callExternalJSFunction() {
sayGoodbye();
}
</script>
test.js file
----------
function sayGoodbye(){
alert("Bye!");
}
------------------------
What is wrong here? why sayGoodbye is get called? how should i do this?
after that I guess it will be easy to send the data as well, but I
cannot even get the function call working now.. :) my brain does not work :)
[toc] | [prev] | [next] | [standalone]
| From | JiiPee <no@notvalid.com> |
|---|---|
| Date | 2015-10-02 13:46 +0100 |
| Message-ID | <11vPx.39900$zs6.8133@fx29.am4> |
| In reply to | #28782 |
On 02/10/2015 12:53, JiiPee wrote: > > > What is wrong here? why sayGoodbye is get called? how should i do > this? after that I guess it will be easy to send the data as well, but > I cannot even get the function call working now.. :) my brain does not > work :) > > > ok, there is something else wrong in my project. I got this working on another project.... so will next test the global variable idea.
[toc] | [prev] | [next] | [standalone]
| From | Ben Bacarisse <ben.usenet@bsb.me.uk> |
|---|---|
| Date | 2015-10-02 13:51 +0100 |
| Message-ID | <87fv1tsaaw.fsf@bsb.me.uk> |
| In reply to | #28782 |
JiiPee <no@notvalid.com> writes:
<snip>
> ok, am currently testing this. But my code in php is not even able to
> call javascript function (in an external file). What am i doing wrong:
>
> php file:
> ------------
> <script type="text/javascript" src="test.js"></script>
>
> ...// some button triggers callExternalJSFunction()
>
> <script>...
> function callExternalJSFunction() {
> sayGoodbye();
> }
> </script>
>
>
> test.js file
> ----------
> function sayGoodbye(){
> alert("Bye!");
> }
> ------------------------
>
> What is wrong here? why sayGoodbye is get called? how should i do
> this? after that I guess it will be easy to send the data as well, but
> I cannot even get the function call working now.. :) my brain does not
> work :)
You are not helping us to help you. Put an actual example online so we
can go and find out what's wrong. If you can't do that, post the actual
files that make up your test.
If you do put up an example, it helps if you also make a text file for
every PHP file. I.e. if your test page is called test.php, you also put
an exact copy called test.php.txt on the server. If you don't do this
we have no way of seeing the PHP code.
--
Ben.
[toc] | [prev] | [next] | [standalone]
| From | Thomas 'PointedEars' Lahn <PointedEars@web.de> |
|---|---|
| Date | 2015-10-02 21:42 +0200 |
| Message-ID | <1624850.oZzQaDyhdP@PointedEars.de> |
| In reply to | #28781 |
Stefan Weiss wrote: > On 2015-10-02 12:58, JiiPee wrote: >> I guess my main question is that if I have a php file how can I send >> data/string from there to a javascript file. >> >> php file: >> contains some data/string >> >> test.js file: >> wants to get hold of that string created in php file > > Ah. Now that the navigation is out of the way, it's simple enough. > test.js has access to the same variables as any inline script in the > document. You can make some_string a global variable; local variables in > functions are never visible outside the function. You can do that, but it is not a good idea to do it. In fact, this is bad advice. There should be as few global variables as possible. Whenever data needs to be available globally, *one* global variable which stores a reference to a native user-defined object should serve as the hub for storing data as values of the properties of that object. The value of the variable or the values of the properties of the referred object, should be passed to and between functions. -- PointedEars FAQ: <http://PointedEars.de/faq> | SVN: <http://PointedEars.de/wsvn/> Twitter: @PointedEars2 | ES Matrix: <http://PointedEars.de/es-matrix> Please do not cc me. / Bitte keine Kopien per E-Mail.
[toc] | [prev] | [next] | [standalone]
| From | Stefan Weiss <krewecherl@gmail.com> |
|---|---|
| Date | 2015-10-03 00:33 +0200 |
| Message-ID | <mun0o8$d9i$1@news.albasani.net> |
| In reply to | #28796 |
On 2015-10-02 21:42, Thomas 'PointedEars' Lahn wrote: > Stefan Weiss wrote: >> test.js has access to the same variables as any inline script in the >> document. You can make some_string a global variable; local variables in >> functions are never visible outside the function. > > You can do that, but it is not a good idea to do it. In fact, this is bad > advice. There should be as few global variables as possible. At this point in OP's learning curve, we are light years away from teaching best practices. He asked how he could access a local variable in a function from an included script file. Suggesting a global variable at this point is, in my personal opinion, the right thing to do. It teaches about scope. Judging from the follow-up, even that presented some problem, which has yet to be solved. Your suggestion about the "one global variable" is correct, but ten steps ahead of where his current priorities lie (i.e., "how do I get this to work" rather than "what's the best way to design this"). For this reason, I reject your critizism of my "bad advice". Both of us have decades of experience with JavaScript, but apparently only one of us has any experience with teaching. - stefan
[toc] | [prev] | [next] | [standalone]
| From | JiiPee <no@notvalid.com> |
|---|---|
| Date | 2015-10-02 23:45 +0100 |
| Message-ID | <KNDPx.23702$oA5.20668@fx32.am4> |
| In reply to | #28797 |
On 02/10/2015 23:33, Stefan Weiss wrote: > global variable" is correct, but ten steps ahead of where his current > priorities lie (i.e., "how do I get this to work" rather than "what's > the best way to design this"). you are right in this: I really had to get this quickly working. Was not really looking for best design this time. I made a lot of code already, it works pretty well (for the user everything goes ok) but the best practices I have to learn later on. > For this reason, I reject your critizism of my "bad advice". Both of > us have decades of experience with JavaScript, but apparently only one > of us has any experience with teaching. - stefan
[toc] | [prev] | [next] | [standalone]
| From | Tim Streater <timstreater@greenbee.net> |
|---|---|
| Date | 2015-10-02 23:55 +0100 |
| Message-ID | <021020152355304297%timstreater@greenbee.net> |
| In reply to | #28797 |
In article <mun0o8$d9i$1@news.albasani.net>, Stefan Weiss <krewecherl@gmail.com> wrote: >On 2015-10-02 21:42, Thomas 'PointedEars' Lahn wrote: >> Stefan Weiss wrote: >>> test.js has access to the same variables as any inline script in the >>> document. You can make some_string a global variable; local variables in >>> functions are never visible outside the function. >> >> You can do that, but it is not a good idea to do it. In fact, this is bad >> advice. There should be as few global variables as possible. > >At this point in OP's learning curve, we are light years away from >teaching best practices. He asked how he could access a local variable >in a function from an included script file. Suggesting a global variable >at this point is, in my personal opinion, the right thing to do. It >teaches about scope. Judging from the follow-up, even that presented >some problem, which has yet to be solved. Your suggestion about the "one >global variable" is correct, but ten steps ahead of where his current >priorities lie (i.e., "how do I get this to work" rather than "what's >the best way to design this"). For this reason, I reject your critizism >of my "bad advice". Both of us have decades of experience with >JavaScript, but apparently only one of us has any experience with teaching. You're quite right. That's definitely not PointyHead. -- Anyone who slaps a 'this page is best viewed with Browser X' label on a Web page appears to be yearning for the bad old days, before the Web, when you had very little chance of reading a document written on another computer, another word processor, or another network. -- Tim Berners-Lee
[toc] | [prev] | [next] | [standalone]
| From | JiiPee <no@notvalid.com> |
|---|---|
| Date | 2015-10-03 00:02 +0100 |
| Message-ID | <U1EPx.28680$fe1.9036@fx12.am4> |
| In reply to | #28796 |
On 02/10/2015 20:42, Thomas 'PointedEars' Lahn wrote: > Stefan Weiss wrote: > >> On 2015-10-02 12:58, JiiPee wrote: >>> I guess my main question is that if I have a php file how can I send >>> data/string from there to a javascript file. >>> >>> php file: >>> contains some data/string >>> >>> test.js file: >>> wants to get hold of that string created in php file >> Ah. Now that the navigation is out of the way, it's simple enough. >> test.js has access to the same variables as any inline script in the >> document. You can make some_string a global variable; local variables in >> functions are never visible outside the function. > You can do that, but it is not a good idea to do it. In fact, this is bad > advice. There should be as few global variables as possible. > > Whenever data needs to be available globally, *one* global variable which > stores a reference to a native user-defined object should serve as the hub > for storing data as values of the properties of that object. The value of > the variable or the values of the properties of the referred object, should > be passed to and between functions. > sounds sound sure. I have c++ background so know this. But yes this time I had just quickly make it working, but sure this is a good advice for the future
[toc] | [prev] | [next] | [standalone]
| From | JiiPee <no@notvalid.com> |
|---|---|
| Date | 2015-10-02 23:49 +0100 |
| Message-ID | <ARDPx.85069$eO3.73494@fx05.am4> |
| In reply to | #28781 |
On 02/10/2015 12:38, Stefan Weiss wrote: > On 2015-10-02 12:58, JiiPee wrote: >> I guess my main question is that if I have a php file how can I send >> data/string from there to a javascript file. >> >> php file: >> contains some data/string >> >> test.js file: >> wants to get hold of that string created in php file > Ah. Now that the navigation is out of the way, it's simple enough. > test.js has access to the same variables as any inline script in the > document. You can make some_string a global variable; local variables in > functions are never visible outside the function. > > > in the final version I changed html to php and did use global js variable to pass data to js from php. I think like you said. I set this global via a function. It worked...
[toc] | [prev] | [next] | [standalone]
| From | Thomas 'PointedEars' Lahn <PointedEars@web.de> |
|---|---|
| Date | 2015-10-02 21:37 +0200 |
| Message-ID | <1739227.XXYPReGQTy@PointedEars.de> |
| In reply to | #28777 |
Stefan Weiss wrote: > On 2015-10-02 09:44, Evertjan. wrote: >>> var some_string = <?php echo json_encode($sometext); ?>; >> >> This is totally errorprone, you need to enclose the litteral string in >> '-s or "-s, ensuring that the ones used do not appear in the inner text. > > No, json_encode() already takes care of quoting and character escaping; > adding extra quotes around the result would be a syntax error. ACK. > That doesn't mean that json_encode() by itself is enough to safely > escape strings as JavaScript literals. What if $sometext contains > "</script>"? Not a problem in HTML5 or XHTML(5), but in HTML < 5. > What actually has to be escaped - in addition to characters like quotes, > newlines, etc - depends on which HTML version is used. > For HTML5, the process and some pitfalls are described here: > http://www.w3.org/TR/html5/scripting-1.html#restrictions-for-contents-of-script-elements > > Short version: > > | Note: The easiest and safest way to avoid the rather strange > | restrictions described in this section is to always escape "<!--" as > | "<\!--", "<script" as "<\script", and "</script" as "<\/script" […] And it is wrong *again* (see below). For example, if you had a RegExp literal in your ECMAScript or Perl code to match “<script” (which as for ECMAScript code can be useful for retrieving embedded data), which would likely be /<script…/, then changing that to /<\script…/ would attempt to match “<”, followed by ECMAScript/Perl whitespace, followed by “cript…” instead. For another example, as can be seen further below that note, the HTML5 Specification (fortunately) does not even define syntax that would require “</script>” in a “script” element to be escaped in any way: | script = outer *( comment-open inner comment-close outer ) | | outer = < any string that doesn't contain a substring that matches | not-in-outer > | not-in-outer = comment-open | inner = < any string that doesn't contain a substring that matches | not-in-inner > | not-in-inner = comment-close / script-open (No “script-close” there.) Presumably, this part of the note incorporates escape recommendations for HTML < 5, where the CDATA content of a SCRIPT element would end when the SGL parser encountered “</” (ETAGO) as it claims that “for historical reasons, parsing of script blocks in HTML is a strange and exotic practice that acts unintuitively in the face of these sequences.” Which *actually* means: The authors of this paragraph did not know what the hell they were doing back then [when they wrote or read the HTML 4.01 Specification], they still do not know, and they are projecting that on their unfortunate readership. The record shows that one cannot trust the authors of HTML Specifications regarding advice relevant to Web programming languages, in particular ECMAScript implementations. (Fortunately, as always, Notes are not normative.) In fact, the easiest and safest way to avoid the issue is to put the script code in a separate file, and use the “src” attribute of the “script” element to include the corresponding resource. Yes, that means another request, but you can’t have everything. >>> So in doSomething I want to be able to use this some_string created in >>> php file. How can I do it? >> So you cannot. >> >> Why don't you create that string on the "index.html" PAGE, >> that you probably will have to rename to "index.php". > > Thats one way to do it. Unfortunately, we don't know enough about OP's > project to give any meaningful advice. For example, if we knew that > `some_string` is relatively short, we could suggest passing it along to > index.html in the query string. > > location.href = "index.html?s=" + encodeURIComponent(some_string); > > The script included from index.html could then read it back from the > query string. It is important to emphasize “relatively short”, because this approach is subject to IE URL length limits which can be easily exceeded if the argument to encodeURIComponent() contains Unicode characters with code points beyond the US-ASCII range (as URI percent-encoding is UTF-8 based). > In general, mixing dynamic and static files (PHP and plain HTML) like > this tends to get messy. It depends on the application. There is no good reason that PHP should parse files in which there are no proper PHP sections, and every reason to avoid that. But doing things client-side that can be done server-side is often not the correct approach. -- PointedEars (Zend Certified PHP Engineer) FAQ: <http://PointedEars.de/faq> | SVN: <http://PointedEars.de/wsvn/> Twitter: @PointedEars2 | ES Matrix: <http://PointedEars.de/es-matrix> Please do not cc me. / Bitte keine Kopien per E-Mail.
[toc] | [prev] | [next] | [standalone]
| From | Stefan Weiss <krewecherl@gmail.com> |
|---|---|
| Date | 2015-10-03 00:34 +0200 |
| Message-ID | <mun0p1$d9i$3@news.albasani.net> |
| In reply to | #28795 |
On 2015-10-02 21:37, Thomas 'PointedEars' Lahn wrote:
> Stefan Weiss wrote:
>> That doesn't mean that json_encode() by itself is enough to safely
>> escape strings as JavaScript literals. What if $sometext contains
>> "</script>"?
>
> Not a problem in HTML5 or XHTML(5), but in HTML < 5.
That is incorrect, see below.
>> | Note: The easiest and safest way to avoid the rather strange
>> | restrictions described in this section is to always escape "<!--" as
>> | "<\!--", "<script" as "<\script", and "</script" as "<\/script" […]
>
> And it is wrong *again* (see below). For example, if you had a RegExp
> literal in your ECMAScript or Perl code to match “<script” (which as for
> ECMAScript code can be useful for retrieving embedded data), which would
> likely be /<script…/, then changing that to /<\script…/ would attempt to
> match “<”, followed by ECMAScript/Perl whitespace, followed by “cript…”
> instead.
What the hell are you rambling about? Nobody said anything about Perl
regexes. I wrote (quoted) that "<script" should be replaced with
"<\script". No regexes, no imaginary errors, just plain string
replacement. Look:
str_replace("<script", "<\script", $some_text);
Done. And even *IF* it was a Perl regex (which is a completely random
and off-topic assumption), the "\s" is in the replacement part, not in
the matching part. In Perl, you'd write
s#<script#<\\script#g;
(or even with a single backslash if warnings are off)
No whitespace is matched anywhere.
> [...] the HTML5 Specification (fortunately) does not even define
> syntax that would require “</script>” in a “script” element to be
> escaped in any way [...] The authors of this paragraph did not know
> what the hell they were doing [...] one cannot trust the authors of
> HTML Specifications regarding advice relevant to Web programming
> languages [...]
It is an awkward area of the specification, I grant you that. They
pretty much acknowledge that when they mention the "rather strange
restrictions". They were trying to remain backward compatible with
existing usage (up to a point), which is why we still have those
slightly absurd edge cases with <!--, <script> etc.
But they did get it right, or at least they and the current user agents
agree. You apparently don't, but you're the odd one out here. By all
means, go ahead and write something like this:
<script>
console.log("This is just a string</script>");
console.log("And this is another");
</script>
If you think that's safe, good luck to you. You're going to need it.
By the way, you also mentioned this wouldn't be a problem in XHTML.
To get a valid XML document, you'll have to escape much more than the
strings I mentioned.
> In fact, the easiest and safest way to avoid the issue is to put the script
> code in a separate file,
Maybe, but that's not what the question was about. It also has nothing
to do with safe escaping of string literals in an HTML document.
Sometimes you have to pass values from the server side to the client
side. If you don't do that in an inline script, you'll have to make the
included script itself dynamic (as in, generated by PHP etc).
>> if we knew that `some_string` is relatively short, we could suggest
>> passing it along to index.html in the query string.
>>
>> location.href = "index.html?s=" + encodeURIComponent(some_string);
...
> It is important to emphasize “relatively short”, because this approach is
> subject to IE URL length limits
Yes, I know, that's why I said "relatively".
In any case, thanks for reminding me why I left this group in the first
place. It was specifically so I don't have to deal with your incessant
and pedantic and pointless nitpicks any longer. Even when you're proven
wrong you would *never* admit to making a mistake. Some scientist you are.
- stefan
[toc] | [prev] | [next] | [standalone]
| From | Thomas 'PointedEars' Lahn <PointedEars@web.de> |
|---|---|
| Date | 2015-10-03 04:35 +0200 |
| Message-ID | <13501800.DmYS3OLCIa@PointedEars.de> |
| In reply to | #28798 |
Stefan Weiss wrote:
> On 2015-10-02 21:37, Thomas 'PointedEars' Lahn wrote:
>> Stefan Weiss wrote:
>>> That doesn't mean that json_encode() by itself is enough to safely
>>> escape strings as JavaScript literals. What if $sometext contains
>>> "</script>"?
>> Not a problem in HTML5 or XHTML(5), but in HTML < 5.
>
> That is incorrect, see below.
My description is not incorrect, but incomplete.
>>> | Note: The easiest and safest way to avoid the rather strange
>>> | restrictions described in this section is to always escape "<!--" as
>>> | "<\!--", "<script" as "<\script", and "</script" as "<\/script" […]
>>
>> And it is wrong *again* (see below). For example, if you had a RegExp
>> literal in your ECMAScript or Perl code to match “<script” (which as for
>> ECMAScript code can be useful for retrieving embedded data), which would
>> likely be /<script…/, then changing that to /<\script…/ would attempt to
>> match “<”, followed by ECMAScript/Perl whitespace, followed by “cript…”
>> instead.
>
> What the hell are you rambling about? Nobody said anything about Perl
> regexes.
Yes, the problem is yet another knee-jerk assertion in yet another HTML
Specification note. There is no regard in it as to how script code is
generated, and as to what script code is intended to do.
> I wrote (quoted) that "<script" should be replaced with
> "<\script".
Which is wrong *in general*, as I have pointed out.
This assertion is in the same sense wrong as is the following one further
below the Specification prose, in another note:
| It is possible for these sequences to naturally occur in script
| expressions, as in the following examples:
|
| if (x<!--y) { ... }
| if ( player<script ) { ... }
|
| In such cases the characters cannot be escaped, but the expressions can be
| rewritten so that the sequences don't occur, as in:
|
| if (x < !--y) { ... }
|
| […]
| [as] for related historical reasons, the string "<!--" in JavaScript is
| actually treated as a line comment start, just like "//".
No, it is not. The problem here is that the authors make the common mistake
and use the term “JavaScript” as an umbrella term, failing to differentiate
between ECMAScript implementations. [1] They also fail to differentiate
between markup parsers’ preprocessing and the parsing of script engines.
And again, instead of modifying your script code to accomodate markup
languages in which it is contained, you are much better off by taking the
offending script code out of the problematic markup context, which can be
easily done, and *fixing the code* which should have never been written this
way in the first place:
For there really is nothing “natural” about this code, in which a variable
or property “y” is pre-decremented [--…] in an *“if”* statement (of all the
things), the resulting value is converted to boolean [!…], and then the
*boolean value* is compared *arithmetically* or as a *string*, depending on
the type of “x”, against another variable or property value “x” [“<”];
*nobody remotely in their right mind writes ECMAScript-based code like
this*. (And then “player<script”? Give me a break.)
[1] <http://PointedEars.de/es-matrix>
> No regexes, no imaginary errors, just plain string replacement. Look:
>
> str_replace("<script", "<\script", $some_text);
>
> Done.
No. (And it is bad practice to use unknown escapes in double-quoted string
literals in PHP. It is also unwise to use double-quoted string literals
where single-quoted string literals would have sufficed, because different
to ECMAScript, double quotes also imply interpolation in PHP [and several
other script languages].)
> And even *IF* it was a Perl regex (which is a completely random
> and off-topic assumption), the "\s" is in the replacement part, not in
> the matching part.
I was talking about code that can be (but does not have to be) contained in
markup, code that uses regular expressions to match and process markup.
That code will be broken by blind escaping to accomodate HTML parsers.
>> [...] the HTML5 Specification (fortunately) does not even define
>> syntax that would require “</script>” in a “script” element to be
>> escaped in any way [...] The authors of this paragraph did not know
>> what the hell they were doing [...] one cannot trust the authors of
>> HTML Specifications regarding advice relevant to Web programming
>> languages [...]
>
> It is an awkward area of the specification, I grant you that. They
> pretty much acknowledge that when they mention the "rather strange
> restrictions". They were trying to remain backward compatible with
> existing usage (up to a point), which is why we still have those
> slightly absurd edge cases with <!--, <script> etc.
>
> But they did get it right,
In convenient edge cases only, which is the problem.
> or at least they and the current user agents agree.
Interesting. As for Chromium 44.0.2403.89 on GNU/Linux, for which I can
confirm that unescaped “</script>” in a “script” element is a problem, this
should be considered a bug as (AFAICS) the given ABNF for the “script”
element content allows “</script>” in it.
It is probably rather a Specification bug than a browser bug, given that an
HTML parser needs a way to recognize the end of the “script” element, and
that this way should be as simple as reasonably possible in order to avoid
greater complexity in the parser. But see below.
> You apparently don't, but you're the odd one out here. By all
> means, go ahead and write something like this:
>
> <script>
> console.log("This is just a string</script>");
> console.log("And this is another");
> </script>
>
> If you think that's safe, good luck to you. You're going to need it.
Straw man. I did _not_ say that I think that it is *safe*. I said that it
is not a problem in those markup languages. Which is correct (in theory).
> By the way, you also mentioned this wouldn't be a problem in XHTML.
I did, and it is not (if you serve XHTML properly).
> To get a valid XML document, you'll have to escape much more than the
> strings I mentioned.
No, as I have said many times before in both in
<news:de.comp.lang.javascript> and here, you just have to declare the
offending “script” element content a part of a CDATA section, and escape the
CDATA section end marker. BTDT:
<script type="text/javascript">// <![CDATA[
// escape “]]>” here if “<” follows
// ]]></script>
Because the XML CDATA type/section is not so ill-defined as the SGML CDATA
content type that its value would end when the parser encountered an ETAGO
(End-TAG Open) delimiter. However, this only applies to markup validation
and to XHTML served as application/xhtml+xml. If you serve XHTML as
text/html instead (which is only necessary if you insist on using XHTML
*and* want to support obsolete browsers such as IE 8), then an HTML parser
is used, and the HTML escaping measures would have to be applied as well.
[“Validate by input” on <http://validator.w3.org/> now recognizes the HTML5
"doctype", and uses the new <http://validator.w3.org/nu/> if you submit the
form and have chosen “Validate Full Document”, and “(detect automatically)”
or “HTML5 (experimental)”.]
But none of this is necessary, regardless of the document type, if you move
the “script” element content to a separate file, and use the “src”
attribute, AISB. Much simpler than considering the document type, escaping
everything based on that; and much safer – namely completely safe. On top
of that, it is easier to maintain, because syntax highlighting and related
features depend less on the capabilities of the used code editor, less on
its ability to recognize the context.
> [whining about leaving the newsgroup]
That is your problem alone. If you can’t stand the heat (of constructive
criticism), and are unwilling to check your assumptions and to participate
in the mutual learning process, (only then it makes sense for you to) stay
out of the kitchen.
IOW: Your logic is flawed. You should learn to control your emotions lest
they control you.
--
PointedEars
FAQ: <http://PointedEars.de/faq> | SVN: <http://PointedEars.de/wsvn/>
Twitter: @PointedEars2 | ES Matrix: <http://PointedEars.de/es-matrix>
Please do not cc me. / Bitte keine Kopien per E-Mail.
[toc] | [prev] | [next] | [standalone]
| From | Stefan Weiss <krewecherl@gmail.com> |
|---|---|
| Date | 2015-10-05 01:11 +0200 |
| Message-ID | <musbm7$cd5$1@news.albasani.net> |
| In reply to | #28804 |
On 2015-10-03 04:35, Thomas 'PointedEars' Lahn wrote:
> Stefan Weiss wrote:
>> I wrote (quoted) that "<script" should be replaced with
>> "<\script".
...
> This assertion is in the same sense wrong as is the following one further
> below the Specification prose, in another note:
[ snip spec note ]
> The problem here is that the authors make the common mistake
> and use the term “JavaScript” as an umbrella term, failing to differentiate
> between ECMAScript implementations.
Oh, here we go again... Don't you ever get tired of this?
>> str_replace("<script", "<\script", $some_text);
>>
>> Done.
>
> No.
...because? A simple unqualified "no" is not good enough.
> (And it is bad practice to use unknown escapes in double-quoted string
> literals in PHP.
"\s" is not an unknown escape, it's two characters. If this offends your
eyes, or you're not sure what is an what isn't an escape sequence in a
PHP string, you're free to use "\\s" or '\s'. The result is the same.
> It is also unwise to use double-quoted string literals
> where single-quoted string literals would have sufficed, because different
> to ECMAScript, double quotes also imply interpolation in PHP [and several
> other script languages].)
Thanks for the lecture, but I'm well aware of how PHP strings work. The
single vs double quote issue has been discussed ad nauseam, and what it
always boils down to is that it's primarily a matter of preference
(which you have a tendency to elevate to laws, for some reason). The
main point is to be consistent.
>> And even *IF* it was a Perl regex (which is a completely random
>> and off-topic assumption), the "\s" is in the replacement part, not in
>> the matching part.
>
> I was talking about code that can be (but does not have to be) contained in
> markup, code that uses regular expressions to match and process markup.
> That code will be broken by blind escaping to accomodate HTML parsers.
Then you're talking about something nobody asked. This is not about
escaping code, it's about escaping the contents of a string in a
<script> element.
> Interesting. As for Chromium 44.0.2403.89 on GNU/Linux, for which I can
> confirm that unescaped “</script>” in a “script” element is a problem, this
> should be considered a bug as (AFAICS) the given ABNF for the “script”
> element content allows “</script>” in it.
It's not just Chrome, you get the exact same behavior in Firefox and
IE/Edge. For once, everyone agrees. There may or may not be an error in
the specification - I only skimmed the quoted ABNF because I'm really
not interested in that. The intention was made well clear in the note
accompanying the formal definition. If there is indeed an error, file a
bug against the specification.
Unescaped "</script>" in a string causes problems, as has been
demonstrated. The problems can be avoided by escaping it as
"<\/script>". This is how it works, and how the specification says it
should work (again, possibly with an error in the details, according to
you).
> I did _not_ say that I think that it is *safe*. I said that it
> is not a problem in those markup languages. Which is correct (in theory).
But not in practice.
>> To get a valid XML document, you'll have to escape much more than the
>> strings I mentioned.
>
> No, as I have said many times before in both in
> <news:de.comp.lang.javascript> and here, you just have to declare the
> offending “script” element content a part of a CDATA section
Then that's a completely different context. You obviously have to use
different escaping in a CDATA section...
> // escape “]]>” here if “<” follows
... but not like that!
> But none of this is necessary, regardless of the document type, if you move
> the “script” element content to a separate file, and use the “src”
> attribute, AISB.
Correct but off-topic.
> If you can’t stand the heat [...blah...] stay out of the kitchen.
There is no heat, there's only you. And despite what you might think,
most of your sermons don't come across as constructive or challenging,
just as tedious and pedantic. My main complaint is that you write in a
very condescending way, all but forcing the other party to write a
rebuttal. This is a tremendous waste of my time.
In other words: I'm avoiding the kitchen for extended periods of time
because it's full of bureaucrats rather than cooks.
Look at this exchange as a perfect illustration. Here we are, at the end
of your very long reply. You blather at length about external script
files, bad practices of writing PHP code, spec authors who don't
subscribe to your "There is no Javascript" philosophy, nitpicks about
the examples in the spec, escaping JS code instead of string contents,
and the HTML5 validator.
And after all that we still have no reason why we shouldn't escape
"</script" as "<\/script", except for a possible error in the
specification. But at least you got to say "No" and call somebody else
wrong.
> IOW: Your logic is flawed. You should learn to control your emotions lest
> they control you.
Somebody's taking their science fiction a little too seriously.
- stefan
[toc] | [prev] | [next] | [standalone]
| From | Tim Streater <timstreater@greenbee.net> |
|---|---|
| Date | 2015-10-05 09:13 +0100 |
| Message-ID | <051020150913451083%timstreater@greenbee.net> |
| In reply to | #28811 |
In article <musbm7$cd5$1@news.albasani.net>, Stefan Weiss <krewecherl@gmail.com> wrote: >On 2015-10-03 04:35, Thomas 'PointedEars' Lahn wrote: >> If you can’t stand the heat [...blah...] stay out of the kitchen. > >There is no heat, there's only you. And despite what you might think, >most of your sermons don't come across as constructive or challenging, >just as tedious and pedantic. My main complaint is that you write in a >very condescending way, all but forcing the other party to write a >rebuttal. This is a tremendous waste of my time. >In other words: I'm avoiding the kitchen for extended periods of time >because it's full of bureaucrats rather than cooks. > >Look at this exchange as a perfect illustration. Here we are, at the end >of your very long reply. You blather at length about external script >files, bad practices of writing PHP code, spec authors who don't >subscribe to your "There is no Javascript" philosophy, nitpicks about >the examples in the spec, escaping JS code instead of string contents, >and the HTML5 validator. And all this instead of giving useful, concise information. PointyHead thinks he's a good teacher, whereas in fact he's one of the worst I've ever seen. A good teacher can impart knowledge to a student at whatever stage they happen to be at, if they can be bothered, by judging the student's state of knowledge and tailoring their reply to that student. Instead, what we see here is button pushing; standard responses come out with no though as to whether they are going to be useful to the OP or not. We can do without this. Thanks, Stefan, for summarising (much better than I could) why PointyHead is an arsehole. -- "Please stop telling us what you feel. Please stop telling us what your intuition is. Your intuitive feelings are of no interest whatsoever, and nor are mine. I don't give a bugger what you feel, or what I feel. I want to know what the evidence shows." -- Richard Dawkins
[toc] | [prev] | [next] | [standalone]
Page 1 of 2 [1] 2 Next page →
Back to top | Article view | comp.lang.javascript
csiph-web