iceangel89
iceangel89

Reputation: 6273

PHP in HTML <Script>

I was viewing a Appcelerator Titanium Video Tutorial and I saw they used syntax like

<script type="text/php">
... 
global $window, $document;
mysql_connect(...) or die $window->alert('...');
$document.getElementById('xxx');

...
</script>

so I have a few questions. Is it any difference if I use <?php ?> without setting $window and $document - won't they be "unset" variables? I guess I can use (basic, not jQuery for example) Javascript functions like alert and getElementById() in PHP too?

Upvotes: 1

Views: 170

Answers (3)

Michael Borgwardt
Michael Borgwardt

Reputation: 346506

For a regular web app, the code you're showing makes no sense whatsoever, because PHP runs on the server and JavaScript runs on the client. PHP is used to build the HTML code which forms the DOM tree on which JavaScript functions like getElementById() operate, so it's completely impossible to use them meaningfully within PHP code.

However, a cursory investigation reveals that Appcelerator Titanium is a sort of runtime that is meant to run applications using web technology completely on the client. In such a runtime, it is possible that the PHP code is running in the context of an already complete HTML DOM and interacts with it via JavaScript-like bridge functions. But that's completely different from how PHP normally works.

Upvotes: 0

Quentin
Quentin

Reputation: 944454

As far as PHP is concerned, there is no JavaScript — only text.

$window and $document are just variables defined elsewhere in the PHP. $window appears to be an object with some methods that output text (text that happens to include JS syntax) while $document appears to be a string.

They will be undefined if they haven't been defined already.

You can write any JS function you like as normal text. If you want to use an object to generate it, then you need to have an object that is aware of that function.

Upvotes: 0

Milan Babuškov
Milan Babuškov

Reputation: 61208

In this case, they can only be "undefined", not "unset". However, they have "global" prefix, so there is a chance they are defined in some other code, possibly even outside your file.

$window->alert(...) probably outputs HTML that reads as javascript alert or a similar function.

You cannot use javascript alert() in PHP, because it is not PHP function.

Upvotes: 2

Related Questions