execute php file in *.js

C

cerr

Hi There,

I have a js file containing my script and would like to populate a
table with file paths with the output from a php file.
i tried to just do a <?php include 'getfile.php';?> within the js file
but that doesn;t seem to work....how can I o this?

Thank you!
Ron
 
J

Jeff North

On Wed, 27 Apr 2011 08:30:04 -0700 (PDT), in comp.lang.javascript cerr
<[email protected]>
| Hi There,
|
| I have a js file containing my script and would like to populate a
| table with file paths with the output from a php file.
| i tried to just do a <?php include 'getfile.php';?> within the js file
| but that doesn;t seem to work....how can I o this?
|
| Thank you!
| Ron

When you view source of your web page is the code as you expected?
 
G

Gregor Kofler

Am 2011-04-27 17:30, cerr meinte:
Hi There,

I have a js file containing my script and would like to populate a
table with file paths with the output from a php file.
i tried to just do a <?php include 'getfile.php';?> within the js file
but that doesn;t seem to work....how can I o this?

Perhaps you should learn the difference between clientside JS and
serverside PHP (unless we are talking about clienside PHP and or
serverside JS, which I doubt).

I goes somehow like that:
(1) Set up an asynchronous XMLHttpRequest by your clientside JS
(2) generate your markup by your serverside script
(3) encode it properly and deliver it as response
(4) let your clientside JS parse this response
(5) keep an eye on possible problems (like those when using innerHTML to
append your markup string)

Gregor
 
D

Denis McMahon

I have a js file containing my script and would like to populate a table
with file paths with the output from a php file. i tried to just do a
<?php include 'getfile.php';?> within the js file but that doesn;t seem
to work....how can I o this?

I *think* the question that you're actually asking is:

"How do I get data from inside a php script on my server into a position
where javascript code running on a client can use it?"

There are various methods, for example you could write out a javascript
section from php code that contained the data:

<?php
echo "<script type=\"text/javascript\">\n";
echo "var filenames;\n";
foreach ($array_of_filenames as $index => $filename) {
echo "filenames['{$index}'] = '{$filename}';\n";
}
echo "</script>\n";
?>

Or you could write a php script that returned javascript source:

<?php
// makejsdata.php
header ("Content-type: text/javascript");
echo "var filenames;\n";
foreach ($array_of_filenames as $index => $filename) {
echo "filenames['{$index}'] = '{$filename}';\n";
}
?>

and then you could call this php file in html as a javascript source file:

<script type="text/javascript" src="makejsdata.php">
</script>

Or you could use the onload event of the page to initiate an AJAX JSON or
XML data exchange to populate the javascript data, or you could find some
other method to do it.

However, first of all it seems that you need a better understanding of
what javascript and php are, and how and where and when each is executed.

Rgds

Denis McMahon
 
A

Andreas Bergmaier

Gregor said:
Am 2011-04-27 17:30, cerr meinte:
Hi There,

I have a js file containing my script and would like to populate a
table with file paths with the output from a php file.
i tried to just do a<?php include 'getfile.php';?> within the js file
but that doesn;t seem to work....how can I o this?

Perhaps you should learn the difference between clientside JS and
serverside PHP (unless we are talking about clienside PHP and or
serverside JS, which I doubt).

[ XMLHttpRequest]

I guess the question was how to get the PHP interpreter process PHP
instructions in a .js file. So this is just the wrong newsgroup.

OT: I assume its a problem with your PHP shorttags configuration.

Bergi
 
T

Thomas 'PointedEars' Lahn

Andreas said:
Gregor said:
Am 2011-04-27 17:30, cerr meinte:
I have a js file containing my script and would like to populate a
table with file paths with the output from a php file.
i tried to just do a<?php include 'getfile.php';?> within the js file
but that doesn;t seem to work....how can I o this?

Perhaps you should learn the difference between clientside JS and
serverside PHP (unless we are talking about clienside PHP and or
serverside JS, which I doubt).

[ XMLHttpRequest]

I guess the question was how to get the PHP interpreter process PHP
instructions in a .js file. So this is just the wrong newsgroup.

OT: I assume its a problem with your PHP shorttags configuration.

(Did you mean _OP_?) PHP's `short_open_tag' setting cannot be the cause, as
the OP is not using short open tags (see above); short_open_tag=0 allows
`<?php …' (but not `<?…'), while short_open_tag=1 allows both `<?php …' and
`<?…' to start a PHP block (which is the problem with it).
<http://www.php.net/manual/en/ini.core.php>

The issue is most likely that the "js file" is not processed by PHP at all;
usually only a filename of *.js.php would do that (although there is a not
recommended server configuration that allows keeping the *.js filename).

You are correct that this is the wrong newsgroup for discussing PHP.
However, how to integrate "js" with e.g. PHP should be on-topic.

An alternative to having PHP process all ("js") files as well (which also
includes having to prepend a suitable header() call as the default Content-
Type is `text/html', on top of the inefficience) is

in foo.php:

<script type="text/javascript">
var client_side_data = <?php echo json_encode($server_side_data); ?>;
</script>
<script type="text/javascript" src="bar.js"></script>
<script type="text/javascript" src="baz.js"></script>

bar.js:

… client_side_data …

This can be automated with server-side scripting; for example, in an MVC-
based application you can have controller methods along the lines of

<?php

class FooController extends Controller
{
…

protected function _prepareHead()
{
…
$this->addClientScriptVar('data', $this->data);
$this->addClientScript('bar.js');
$this->addClientScript('baz.js');
…
}

protected function _getData()
{
…
$this->data = ModelMapper::getData();
…
}

…
}

?>

that would cause client-side code to the effect of the above code to be
generated. (We are doing something like this in a Zend Framework/Ext JS-
powered *internal* Web application. [No, Ext JS was not my decision to
make, and I could not do anything about it when I joined the project.
Suffice it to say that I was glad that they had not chosen jQuery or worse
instead.])

The advantage of this is that you can define runtime modes from the server-
side: a debug mode where the included client-side scripts still contain all
formatting and inline documentation; and a production mode where they are
combined into one large script, devoid of all comments, and even
automatically minimized.

The FAQ
<http://webcache.googleusercontent.com/search?q=cache:http://jibbering.com/faq/#getServerVariable>,
which original is currently offline again (as is the Internet Wayback
Machine), should be complemented with this or a similar suggestion.

Another possibility is XMLHttpRequest; that approach can also be combined
with the aforementioned one (and in our application we are doing so).


PointedEars
 
T

Thomas 'PointedEars' Lahn

Denis said:
I have a js file containing my script and would like to populate a table
with file paths with the output from a php file. i tried to just do a
<?php include 'getfile.php';?> within the js file but that doesn;t seem
to work....how can I o this?

I *think* the question that you're actually asking is:

"How do I get data from inside a php script on my server into a position
where javascript code running on a client can use it?"

There are various methods, for example you could write out a javascript
section from php code that contained the data:

<?php
echo "<script type=\"text/javascript\">\n";
echo "var filenames;\n";
foreach ($array_of_filenames as $index => $filename) {
echo "filenames['{$index}'] = '{$filename}';\n";
}
echo "</script>\n";
?>

*Please* DON'T. The least that should be done about this (because it simply
does not work this way, `undefined' does not and cannot have properties) is

<script type="text/javascript">
var filenames = {};
<?php
foreach ($array_of_filenames as $index => $filename)
{
echo "filenames['" . addslashes($index) . "'] = '"
. addslashes($filename) . "';\n";
}
?>
</script>

(see also the FAQ). Even better would be

<script type="text/javascript">
var filenames = {
<?php
foreach ($array_of_filenames as $index => $filename)
{
$out[] = sprintf("'%s': '%s'",
addslashes($index), addslashes($filename));
}

echo join(",\n", $out);
?>
}
</script>

Probably best would be the JSON-based approach I presented earlier.
Or you could write a php script that returned javascript source:

<?php
// makejsdata.php
header ("Content-type: text/javascript");
echo "var filenames;\n"; ^^^^^^^^^^
foreach ($array_of_filenames as $index => $filename) {
echo "filenames['{$index}'] = '{$filename}';\n"; ^^^^^^^^^^
}
?>

This cannot work, see above.
and then you could call this php file in html as a javascript source file:

<script type="text/javascript" src="makejsdata.php">
</script>

That often carries with it the disadvantage that either a PHP editor (incl.
syntax highlighting) is used for what is essentially an ECMAScript-based
script, or that an ECMAScript-based editor is used for the PHP parts as
well.

Not recommended.
Or you could use the onload event of the page to initiate an AJAX JSON or
XML data exchange to populate the javascript data,

Not recommended on a public Web site, for what about no-script people, what
about search engine robots?
or you could find some other method to do it.

Yes, please.
However, first of all it seems that you need a better understanding of
what javascript and php are, and how and where and when each is executed.

Full ACK.


PointedEars
 
C

cerr

Gregor said:
Am 2011-04-27 17:30, cerr meinte:
Perhaps you should learn the difference between clientside JS and
serverside PHP (unless we are talking about clienside PHP and or
serverside JS, which I doubt).
[ XMLHttpRequest]

I guess the question was how to get the PHP interpreter process PHP
instructions in a .js file. So this is just the wrong newsgroup.

OT: I assume its a problem with your PHP shorttags configuration.

Do you, why so? in other files <?php code(); ?> executes just well...
or is there something in the config that tells me which file
extensions should be interpreted and which shouldn't?
 
C

cerr

I *think* the question that you're actually asking is:
"How do I get data from inside a php script on my server into a position
where javascript code running on a client can use it?"
There are various methods, for example you could write out a javascript
section from php code that contained the data:
<?php
echo "<script type=\"text/javascript\">\n";
echo "var filenames;\n";
foreach ($array_of_filenames as $index => $filename) {
echo "filenames['{$index}'] = '{$filename}';\n";
}
echo "</script>\n";
?>

*Please* DON'T.  The least that should be done about this (because it simply
does not work this way, `undefined' does not and cannot have properties) is

  <script type="text/javascript">
    var filenames = {};
<?php
    foreach ($array_of_filenames as $index => $filename)
    {
      echo "filenames['" . addslashes($index) . "'] = '"
        . addslashes($filename) . "';\n";
    }
?>
  </script>

(see also the FAQ).  Even better would be

  <script type="text/javascript">
    var filenames = {
<?php
      foreach ($array_of_filenames as $index => $filename)
      {
        $out[] = sprintf("'%s': '%s'",
          addslashes($index), addslashes($filename));
      }

      echo join(",\n", $out);
?>
    }
  </script>

Probably best would be the JSON-based approach I presented earlier.
Or you could write a php script that returned javascript source:
<?php
// makejsdata.php
header ("Content-type: text/javascript");
echo "var filenames;\n";

            ^^^^^^^^^^
foreach ($array_of_filenames as $index => $filename) {
echo "filenames['{$index}'] = '{$filename}';\n";         ^^^^^^^^^^
}
?>

This cannot work, see above.
and then you could call this php file in html as a javascript source file:
<script type="text/javascript" src="makejsdata.php">
</script>

That often carries with it the disadvantage that either a PHP editor (incl.
syntax highlighting) is used for what is essentially an ECMAScript-based
script, or that an ECMAScript-based editor is used for the PHP parts as
well.

I don't quite understand. Why would I not be able to put the whole
javascript code into my php file and just echo it as Denis explained
it, I'm not following - also, why does my php code not execute when
called from the js file?
All I see when I call http://quaaoutlodge.com/themes/Quaaout11/photoshuffler.js
 
V

VK

I don't quite understand. Why would I not be able to put the whole
javascript code into my php file and just echo it as Denis explained
it, I'm not following - also, why does my php code not execute when
called from the js file?

Because in order to save server resources PHP processing is not
applied to every single file requested from the server. It applies
only to file extensions specifically indicated as "pre-process with
PHP". Normally by default these are only files with .php extension.
Other files including .html and .js extension being sent verbatim.
 
C

cerr

Andreas said:
Gregor said:
Am 2011-04-27 17:30, cerr meinte:
I have a js file containing my script and would like to populate a
table with file paths with the output from a php file.
i tried to just do a<?php include 'getfile.php';?>  within the js file
but that doesn;t seem to work....how can I o this?
Perhaps you should learn the difference between clientside JS and
serverside PHP (unless we are talking about clienside PHP and or
serverside JS, which I doubt).
[ XMLHttpRequest]
I guess the question was how to get the PHP interpreter process PHP
instructions in a .js file. So this is just the wrong newsgroup.
OT: I assume its a problem with your PHP shorttags configuration.

(Did you mean _OP_?)  PHP's `short_open_tag' setting cannot be the cause, as
the OP is not using short open tags (see above); short_open_tag=0 allows
`<?php …' (but not `<?…'), while short_open_tag=1 allows both `<?php …' and
`<?…' to start a PHP block (which is the problem with it).  
<http://www.php.net/manual/en/ini.core.php>

The issue is most likely that the "js file" is not processed by PHP at all;
usually only a filename of *.js.php would do that (although there is a not
recommended server configuration that allows keeping the *.js filename).

Yep, I ended-up renaming my file to .js.php and that seems to work
just fine. I leave it like this for now... to what kind of problems
coudl this possibly lead?

Thanks,
Ron
You are correct that this is the wrong newsgroup for discussing PHP.  
However, how to integrate "js" with e.g. PHP should be on-topic.

An alternative to having PHP process all ("js") files as well (which also
includes having to prepend a suitable header() call as the default Content-
Type is `text/html', on top of the inefficience) is

in foo.php:

  <script type="text/javascript">
    var client_side_data = <?php echo json_encode($server_side_data); ?>;
  </script>
  <script type="text/javascript" src="bar.js"></script>
  <script type="text/javascript" src="baz.js"></script>

bar.js:

  … client_side_data …

This can be automated with server-side scripting; for example, in an MVC-
based application you can have controller methods along the lines of

<?php

class FooController extends Controller
{
  …

  protected function _prepareHead()
  {
    …
    $this->addClientScriptVar('data', $this->data);
    $this->addClientScript('bar.js');
    $this->addClientScript('baz.js');
    …
  }

  protected function _getData()
  {
    …
    $this->data = ModelMapper::getData();
    …
  }

  …

}

?>

that would cause client-side code to the effect of the above code to be
generated.  (We are doing something like this in a Zend Framework/Ext JS-
powered *internal* Web application.  [No, Ext JS was not my decision to
make, and I could not do anything about it when I joined the project.  
Suffice it to say that I was glad that they had not chosen jQuery or worse
instead.])

The advantage of this is that you can define runtime modes from the server-
side: a debug mode where the included client-side scripts still contain all
formatting and inline documentation; and a production mode where they are
combined into one large script, devoid of all comments, and even
automatically minimized.

The FAQ
<http://webcache.googleusercontent.com/search?q=cache:http://jibbering....>,
which original is currently offline again (as is the Internet Wayback
Machine), should be complemented with this or a similar suggestion.

Another possibility is XMLHttpRequest; that approach can also be combined
with the aforementioned one (and in our application we are doing so).

PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
  -- from <http://www.vortex-webdesign.com/help/hidesource.htm> (404-comp.)
 
J

Jeff North

On Wed, 27 Apr 2011 20:56:36 -0700 (PDT), in comp.lang.javascript cerr
<[email protected]>
<b974d350-734b-4523-b242-22d15fa5085f@h36g2000pro.googlegroups.com>
wrote:

[snip]
| I don't quite understand. Why would I not be able to put the whole
| javascript code into my php file and just echo it as Denis explained
| it, I'm not following - also, why does my php code not execute when
| called from the js file?
| All I see when I call http://quaaoutlodge.com/themes/Quaaout11/photoshuffler.js
| is <?php include 'getfile.php'?> at the position where the ouput from
| the file should appear.... :(

What is the file extension of your web page - htm(l) or php?

[snip 2 end]
 
C

cerr

Because in order to save server resources PHP processing is not
applied to every single file requested from the server. It applies
only to file extensions specifically indicated as "pre-process with
PHP". Normally by default these are only files with .php extension.
Other files including .html and .js extension being sent verbatim.

Exactly this must have been the problem, renaming my file to js.php
did the trick....

Thanks to everyone for all the replies!
Ron
 
T

Thomas 'PointedEars' Lahn

Jeff said:
What is the file extension of your web page - htm(l) or php?

That question is wannabe-ish nonsense in itself (there are no "web pages",
and if there were they would not have "file extensions"), and irrelevant to
begin with.

What matters is the resource name of the hybrid server-side/client-side
script, and, if it is not ending in .php[3-6]?, the server configuration;
for example, one possibility on Apache is to have foo.js.php and use
MultiViews to access it with foo.js regardless. However, the source file
would still be foo.js.php, which could affect code editing, e.g. syntax
highlighting, negatively with regard to the client-side script (only the
small portion between `<?php' and `?>' might be highlighted). And one would
need to use PHP's header('…') function to serve it with the proper MIME
media type. Which is why I recommended the mixed approach that does not
have those drawbacks already.


PointedEars
 
J

John G Harris

(there are no "web pages",

Well, what do you call them? A single http transfer can, and sometimes
does, carry more than one HTML document and most browsers will display
the result in one window. 'Page' is a legitimate name for the resulting
display.

Obviously, if the http data is produced on demand by software in the
server then the result is held in a heavily encoded form in the server,
but that's no good reason for insisting on a different name for it in
that form.

and if there were they would not have "file extensions")
<snip>

They are meaningful to the server. Some values tell the server that the
URI contains a filename of a file to be sent with a particular MIME
type. Other values tell the server to hand over processing to some
particular software, which might or might not extract a file name from
the URI.

Calling it a 'file extension' is better than nothing, even if, for
instance, '.jsp' is only a real file extension name on the first use of
that URI.

John
 
D

Denis McMahon

Well, what do you call them? A single http transfer can, and sometimes
does, carry more than one HTML document and most browsers will display
the result in one window. 'Page' is a legitimate name for the resulting
display.

Web servers receive requests from user agents, which generally relate to
files on the server.

These files are processed using various rules embedded in the server
configuration, and possibly by various other software on the system that
the server runs on, and the resulting output is then sent as a file to
the requesting user agent.

If the user agent is a web browser, it may then assemble the received
files into some sort of displayable content, but the server doesn't know
anything about that.

The server may not know what the user agent is. The user agent may even
actively deceive the server as to it's identity. I often use both wget
and curl with various browser user agent strings to see whether servers
are serving different output to different browsers.

Rgds

Denis McMahon
 
J

John G Harris

Web servers receive requests from user agents, which generally relate to
files on the server.

These files are processed using various rules embedded in the server
configuration, and possibly by various other software on the system that
the server runs on, and the resulting output is then sent as a file to
the requesting user agent.

If the user agent is a web browser, it may then assemble the received
files into some sort of displayable content, but the server doesn't know
anything about that.

The server may not know what the user agent is. The user agent may even
actively deceive the server as to it's identity. I often use both wget
and curl with various browser user agent strings to see whether servers
are serving different output to different browsers.

Well, yes, but what do you call the thing that is displayed by a web
browser ?

John
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top