David Williams wrote on 29 okt 2007 in comp.lang.javascript:
Hello all,
I am having a really hard time mixing javascript and php together.
Does anyone know of a good webpage or FAQ that talks about what the
rules are?
If you mean by "javascript" clientside javascript running in the browser.
and by PHP a serverside language running on the server,
it can safely be said they do not mix.
The server, perhaps using PHP, or ASP-javascript renders a [usually html]
stream, that is sent to the client browser and that DOES NOT contain any
PHP or other serverside codes.
Do a view-source on your browser and you will notice tha absense.
Of special note:
Can we use multiple <script></script> enclosures in a document like we
do with <?php ?> or is that forbidden?
Does it "work"? Did you try?
I would guess testing is better than theory for you on this Q.
With "document" one can mean many things, but I like it this way:
A php-file on the server can be called to run on the servers php engine.
The resulting html stream is sent to the client.
That steam running on the browser as a DOM document.
Can I make a databsae connection using php inside of <script></script>
tags if I separate using <? ?> tags.
Since serverside code has stopped running when
<script type='text/javascript'></script> is executed on the client:
NO, no serverside action is possible AT CLIENTSIDE RUNTIME.
[AJAX cloaking of later server/client interaction goes to far for the
moment]
These are just a few of the problems I am having mixing the two not to
mention the huge problem of php not being able to read a javascript
var without resubmitting the page since php is server side and
javascript is client side.
Yes, that is the nature of things, but has nothing to do with the two
languages as such, but with the fact the they run on different machines.
Running two kinds of Javascript,
one on an [ASP] server and the other on the browser is very possible,
like this:
<script type='text/javascript'>
<script language='javascript' runat='server'>
var serversideVariable = 17
response.write('var clientsideVar = "' + serversideVariable + '
;');
</script>
alert(clientsideVar );
</script>
I would not call that mixing myself,
as they are separated by their running time.
I do not speak PHP, but the possibility should be the same.