JS, PHP, Html File Conventions - javascript

I have 3 questions, but I think the first 2 are very simple, so I'll ask them all here.
I normally work in C++ with SQL (and sometimes with VBA), and I'm trying to figure out the basics of JS, PHP & HTML (I've mostly got the jist of HTML and CSS).
I have 5 different reference books plus the net, but one thing I can't seem to find anything about are the file exts (.js, .php, .html).
From my tests I have come to realize that you can usually run JS scripts in other file types, but PHP seems to require the .php ext.
So the questions are:
Do I always have to use *.php for PHP scripting?
In a SINGLE file, can I delay PHP execution by simply putting the code into a function?
eg
<?php
function test() {echo "hello world";}
//as opposed to:
echo "hello world";
?>
When using multiple files, are there any compelling reasons to (or not to) always put scripts in their corresponding file types (e.g. JS in *.js). Obviously this would make it easier to understand / read, especially as it grows BUT can this create problems?

No, you can use any extension you want. Even if you want, don't use extension at all. But then, tell your server what interpreter to use when he founds he has to parse a *.wtf file. I mean, you're running a the script "file.wtf" from the command line you can do it like this:
$>php file.wtf
but if the script is to be parsed by your favorite web server (like Apache) because it is part of (say) a web page, then you have to configure it to interpret .wtf files with the PHP library.
By simply putting it in a function:no. But you really want to delay execution, use the sleep function
Just what you said: You can mix html and javascript code in your php files, but that is very messy.

Related

execute javascript from php

Sorry for this beginner question, I never used js server-side before.
here is my problem:
I have some javascript downloaded from a remote page (it's encrypted, I can't convert it to php), I need to execute it and read its output.
How can I do it? I'm thinking about something like this:
shell_exec('nodejs code...')
but how to pass the code? It's quite long, about 10 lines of javascript.
Another way would be to store the js to a file and run nodejs script.js, but that would be a useless and slow disk IO...
Important caveat about using exec/shell_exec
I feel the need to prepend a caveat about security to this answer. Always be careful when using exec or shell_exec. You almost always should not be taking data over the network to inject into a shell command for security reasons. Writing the script to a file would be much safer because there is no risk of command injection. If you are confident that this approach is required then I strongly advise you to.
Use the PHP function escapeshellcmd which will try to escape shell control characters.
Really ask yourself how much you trust the source? And how much you trust their security?
Having said that. Here's my original answer to the question as asked:
It sounds like the missing piece for your puzzle is the -e parameter for node. This will allow you to pass a script as part of the command invocation.
E.g.
C:\Users\Cmonahan>node -e "console.log('hello world');"
hello world
You can then use PHP exec or shell exec to get the output.
More information:
PHP shell_exec() vs exec()
Node CLI documentation
Edit: Regarding passing multiline arguments to the command line. This can be a bit of a minefield. For example: It depends on whether it is a Unix-like or Windows environment and then, if Unix-like, what shell is parsing the command.
See for example:
Windows: How to specify multiline command on command prompt?
End of line (new line) escapes in bash
I would recommend just making sure the argument is a single line. In the case of JS you can try minification first, which typically strips out all newlines, and see if that works for you.
Here's a popular PHP based minifier https://github.com/mrclay/minify I believe you should be able to install via composer.
dont know am not that at home with php, with isnt it true that php serves html files to the user at home, so why would it be any different from using a javascript file in a normal html page?
cant you just use:<script src="myscripts.js"></script>"
or <script>"with here your script"</script>
in the file that need to load this javascript?

Loading Coldfusion javascript asynchronously?

Whenever a page is loaded with Coldfusion, it loads many default Coldfusion javascripts. When I run the Goolge PageSpeed Tools, it always complain about the render-blocking JavaScript. Apparently, Coldfusion has many javascript when a page is loaded such as
...scripts/ajax/yui/yahoo-dom-event/yahoo-dom-event.js
...scripts/ajax/yui/aniax/yui/autocomplete/autocomplete-min.js
...scripts/ajax/yui/autocomplete/autocomplete-min.js
...scripts/ajax/messages/cfmessage.js
...scripts/ajax/package/cfajax.js
...scripts/ajax/package/cfautosuggest.js
...scripts/cfform.js
...scripts/masks.js
These all are considered render-blocking scripts. I can't find any information on how to make them none-render-blocking because obviously I can't add the async="async" parameter to the Coldfusion script which I can't see. How can I make the Coldfusion script none-render-blocking or am I stuck with it?
Can someone please shed some lights?
If you really wanted to do something about this instead of rewriting your UI code, you can actually grab the output from the buffer before it is sent to the client and modify it. Your modifications could be as simple as removing a hardcoded list of script tags and replacing them with a custom script file that you host in your webroot. The custom script file would simply be all of the other script files' contents combined.
To do this:
In onRequestEnd in application.cfc you can call var outputBuffer = getPageContext().popBody().getBuffer() which will return the body to be sent to the client.
Run replacements on outputBuffer, looking for those script tags and removing them via regular expressions. You'll want to keep track of whether or not you've actually removed any to use as a flag in the next step.
Finally, you would append to the output with your new master script tag if your flag that replacements have been made is true. After you do that, the buffer will be automatically flushed to the client.
I believe that Adobe no longer updates the script files, so you basically don't have to worry about versioning your master script file to clear the browser cache.
Edit/Note: Definitely avoid using the CF UI stuff, but we don't know what your situation is like right now. If you have hundreds or thousands of hours of rewriting to do, then obviously rewriting it all is likely not something that is practical at this time.

How does php know when interpret and when to output?

I recently tried including JavaScript using PHP as such:
<?php include 'iife.SomeFile.js';?>
I did not expect it to work, b.c. I thought it would try to interpret the JS as PHP, but instead it just included the file as I asked it.
Is it b.c. I simply omitted the <?php tag that it chose to output the file as text.
Makes me wonder if I can include pretty much any type of file I want.
Also, makes the purpose of SSI seem redundant.
Because this is a valid PHP file:
<html>
...
<script>
var foo = 'bar';
</script>
You may notice that there's no PHP at all in this file, yet it's still valid. That's because PHP was designed as an embedded language to be used in HTML, delimited by the <?php ?> tags. PHP passes anything that's not in those tags through as is.
Also, makes the purpose of SSI seem redundant.
The existence of one language does not make another redundant. Many languages overlap with many other languages in what they can do. Doesn't mean we should all be using just one language. For one, SSI is a lot more lightweight than a full-blown PHP instance if all you want is to include a file.
PHP includes work the same way includes for languages such as C. They simply include or insert the file at that point.
It's just like typing in that entire file yourself where you put the include.
PHP code is executed on the server side. JavaScript is executed on the client side (except with node.js)
The include statement is used to include PHP code. You can use it to include a php lib file in your code.

Include a JavaScript file as it was written in a script tag

I have some html, that had a bunch of JS code inside a script tag. So I moved it to a separate .js file.
JS code also loaded some variables from CGI, using strings in a form of <%ejGet(var)%>. But after separating the code from HTML file, the strings don't get replaced with data from the server.
Is there a way to include a JS file as if it was written inside a script tag or is there another way to do this?
<script language="javascript">
<!-- hide
var syncNvram = '<%ejGetWl(wlSyncNvram)%>';
...about 1000 lines more...
</script>
So after moving this code to a separate file, the variables don't load.
The problem is that your <% ejGetWl(wlSyncNvram) %> is being executed on the server by some templating or processing engine before it gets sent to the browser, so the browser is actually seeing the output, e.g.
var syncNvram = 'abcdefg'; // or whatever the output is
The question you are really asking is, can my server side templating/processing engine process a javascript file as opposed to an html file.
The answer is, it depends on the template/processing engine, but in general, this is a bad idea. JS files should remain static assets for lots of good reasons (breaking code, distributing via CDNs, etc.)
The better thing to do is separate them out:
<script>var syncNvram = '<%ejGetWl(wlSyncNvram)%>';</script>
<script src="myfile.js"></script>
Declare it separately.
Even better might be using ajax to get it, but that is a whole different architecture which may not suit here.
To do that you need to generate the script from the CGI program.
<script src="/cgi-bin/example.js.cgi"></script>
Of course, that will be a different CGI program so getting the variables in the right state may be problematic.
Usually you would solve the problem using a different approach: include the data in the document (either in the script element or in an element such as a <meta> element, a hidden input or a data-* attribute on something relevant and then have a static script read the data from the DOM.

Read/Write file causing errors. (javaScript & C++)

I have a piece of javaScript that works (alongside html) to produce the GUI for a program written in C++. The program has to run for a long time (Sometimes 14/15 days, without monitoring).
The C++ and javaScript communicate by writing to/reading from a XML file.
After running the program for over 24 hours at a time, I've noticed the occasional javaScript error appearing 'someArray[...].name' is null or not an object.
Now: These are all arrays that are filled with information taken from the XML file, written by the C++. The contents of these arrays are refreshed every few seconds (To update information in the GUI 'live').
Question is: Could these errors be caused by an access/timer problem as in --> The javaScript starts reading a line from the XML just as the C++ swoops in and rewrites that line. Therefore information is parsed into the javaScript arrays with some illegal characters (etc) which when accessed throws the errors?
Hope that all makes sense. Thanks.
Your suggestion seems to provide a plausible explanation of what's happening.
You're probably seeing a race condition.
To fix it, you could implement a synchronization mechanism between C++ and JS.
The simplest form of sync I can think of is creating a second file each time C++ writes to your main XML file (this file acts as a lock). JS waits for the lock file to disappear before reading the XML. The same is done on the C++ side.
Sample code:
C++:
while(programRunning) {
do stuff;
// Now it's time to write XML
while("lockCpp.txt" exists)
; // Do nothing, JS is reading
create file "lockJS.txt";
write to xml;
delete file "lockJS.txt";
}
JavaScript:
while(programRunning) {
do stuff;
// Now it's time to read XML
while("lockJS.txt" exists)
; // Do nothing
create file "lockCpp.txt";
read xml;
delete file "lockCpp.txt";
}
This should in practice eliminate race conditions (though some are theoretically, possible, but unlikely).
Should JS not be allowed to write to the file system, then you could remove one of the lock files (lockCpp.txt) and, if the reading on the JS side is normally faster then the writing, it should still eliminate most conflicts.
EDIT after comment:
If you only have access to JS, you could check that the XML document is complete when reading, e.g. the root element is correcly matched by a </rootElementName> at the end.
That will ensure the file write is complete provided C++ doesn't do writes at random locations, but always rewrites the whole document.
Another route would be checking the file is not changing over time. If C++ only sporadically writes to XML, you can read it a few times over a few, say, seconds, and, if unchanged, use the read value. If changed, keep waiting.
HTH

Categories

Resources