Add JavaScript in head - javascript

I understand that good practice is to add the .js files in head of HTML.
My problem is that one of my .js files (or code+script) also has a beginning function, and it looks something like this (and all this is now in head):
<?php
// Countdown timer
function timer($date, $id){ ?>
<script>
(function()
{
// random stuff
}
</script>
// end function timer
<?php } ?>
How should I include/require or <script> src=" x "</script> this kind of file in the head of my HTML? I have hard time figuring out how to add this file in the proper way because of the beginning function.

First of all, replace this:
<script> src=" x "</script>
with this:
<script src=" x "></script>
Now if I understand it correctly you want to include a .php file into the HTML header of your page, and this .php file should include a js script.
Something like:
index.html
<head>
<title>My Weird App</title>
<?php include "myphpfile.php" ?>
</head>
myphpfile.php
<?php
some_func() { ?>
<script src="myjsfile.js"></script>
<?php } ?>
myjsfile.js
function some_other_function() {
//do stuff
}
If you want to execute some javascript code when your php function gets called. This would do, but if you're hoping to be able to use some value returned from php on javascript, or the other way around, then it won't work as you expected. The preferred method of client/server communication is AJAX.
If you want to include the .js file based on a condition, this is done better by:
myphpfile.php
<?php
some_func(some_params) {
if(some_cond) {
return "<script src="myjsfile.php"></script>\n"
} else {
return "";
}
}
?>
then on index.html
<head>
<title>My not so weird app</title>
<?php
include 'myphpfile.php';
echo some_func(some_arguments);
?>
</head>
Well, I hope that helps, if I didn't get it, please comment, (or make your question clearer).

Related

How to include inline JS files with PHP?

Normally that is how one includes JS files in HTML:
<script type="text/javascript" src="myFile.js" ></script>
But I want to write the JS file inline the HTML, using PHP; but still having the possibility of having my neat JS file, that can be chached, debugged and minified.
How can I do something like this?
<script>
<?php include 'myFile.js';?>
</script>
In other words, how to include a JS file in HTML on the server-side. That may get a lot of advantages because it is transparent to the browser.
How can I do something like this?
<script>
<?php include 'myFile.js';?>
</script>
Exactly that code would work, yes. Though it would try to interpret the file as PHP code, and if anything looked like <?php .. ?> inside that file you may see weird side effects. If you want to include the file uninterpreted, simply do:
<script><?php echo file_get_contents('myFile.js'); ?></script>
Be aware of possibly having to escape "</script>" now, should that appear in your included file; see https://stackoverflow.com/a/6908901/476.
YOu need to make custom function or use :
echo '<script type="text/javascript" src="myFile.js" ></script>';
Or
function add_js($filename){
return '<script type="text/javascript" src="'.$filename.'" ></script>';
}
echo add_js('myFile.js');

How to call custom.js file in for loop and i want pass some argument with this js

How to call customs.js file in for loop and i want pass some argument with this js,And how to retrieve this var in JavaScript file.
for($i=0;$i<5;$i++)
{
<script type="text/JavaScript" src="http://localhost/customs.js?var=test'">
}
A better way to do this would be to include your custom.js in the html of the webpage and wrap it's code in a function to which you can pass a variable, like so:
<html>
<head>
<script type="text/JavaScript" src="http://localhost/customs.js"></script>
</head>
<body>
<!-- Your HTML -->
<script>
<?php
for($i=0; $i<5; $i++){
echo "custom(".$myvar.");";
}
?>
</script>
</body>
</html>
Then in your custom.js file you can do this:
function custom(input){
//Do something
}
I should note that you should be careful inserting unsanitized PHP into html directly. For more info, see: How to prevent XSS with HTML/PHP?

a javascript function called by javascript echoed by php doesn't response

I executed 2 javascript function, echoed by php code, in different ways. here is code.
<head>
<script>
aJavascriptFunction(){
document.write( 'php echo writted javascript to call another javascript function ,outside php echo, that write this html' );
}
</script>
</head>
<html>
<head>
</head>
<body>
<?php
echo "<script>document.write('php echo writted javascript to write this html')</script>"; //first case
echo "<br>";
echo "<script>aJavascriptFunction();</script>"; //second case
?>
</body>
</html>
first case, echoed javascript code that directly make function, works well. but second case that echoed javascript code that call another javascript function outside php echo doesn't work.
Could anyone explain why first case works well, but second case doesn't work?
I'm making php file that contain html, javascript and php code inside 'a' file index.php. I want to write html code basically by php echo function. What I'm trying to do is defining javascript functions, php functions separately to call from anywhere in html code(in same file) written by php echo function. I think that separating javascript and php code by separate file will be ultimate answer to my project. but for now, I'm not completely understanding how javascript and php code works in client and server. so, I need to complete my project using style above and remain understanding for latter.
Your code is kinda messy so it is hard to work with. But I will tell you this:
Syntax Error on line 14, unexpected <
It is an issue with your quotes and semicolons.
You have messed up your code.
<html>
<head>
<!-- Your script has to be inside head or body -->
<script type="text/javascript">
// Here is a valid javascript function
function myTestFunction(){
// Print inside browser console
console.log('I was executed.');
// Anyway if need to write
document.write('I was executed.');
}
</script>
</head>
<body>
<?php
echo '<script type="text/javascript">myTestFunction();</script>';
?>
</body>
</html>

Is it possible to put a javascript function in a php file?

Non-programmer here, trying to figure something out.
I have a javascript function in the header of my document that upon page load it opens another page in an iframe and reveals an svg file on my server for minor online editing. I would like to place my javascript function in a php file, so that these folder locations of the svg files cannot be determined for anyone to download these svg files freely.
Currently I have this on my html header:
<script type="text/javascript">
function loaded()
{
document.getElementById("myiframe").src="http://www.mydomain.com/myfolder/mypage.html?url=myotherfolder/"+window.location.search.substr(1);
}
onload=loaded;
</script>
Since I have heard that php is a server side script and not viewable, I thought this would mask the location of these files on my server.
I want to remove this javascript code from my header and place it in a php file and replace the header code with either of these:
<script src="phpjavafile.php"></script>
or
<?php include ('phpjavafile.php'; ?>
and finally put the javascript into a php file like this:
<?php
<script type="text/javascript">
function loaded()
{
document.getElementById("myiframe").src="http://www.mydomain.com/myfolder/mypage.html?url=myotherfolder/"+window.location.search.substr(1);
}
onload=loaded;
</script>
?>
I have tried both of these methods and neither load properly.
I must be doing something wrong. Am I on the right track, or is there a better way of getting this to work.
Thank you ahead of time.
By using the echo() function
PHP
<?php
echo '<script>
some javascript
</script';
?>
However if you are just trying to load the php on page load without any php args then just write it out of the tags.
If you have the JavaScript is another file then using
PHP
<?php
include 'path/to/javascript/file.php';
?>
Should work.
You cannot hide javascript as it is interpreted browser side and not server side so the users browser has to have accesses to the code.
Here is the code I think you are asking for:
PHP HTML
<?php
$html = file_get_contents("path/to/data.html");
?>
<div>
<?php echo $html; ?>
</div>
doesn't use an iframe but should still work. However any relative links will not work unless both files are in the same dir and there will be no iframe functionality without additional css
You can just output it as text in your PHP file.
<?php
// Some PHP stuff here
?>
<script type="text/javascript">
function loaded(){
....
}
onload=loaded;
</script>
<?php
// Some more PHP stuff here
?>
Alternatively, you can just link to it in the usual way from within the same file:
<script src="path/to/your/file.js"></script>

Change the default browser behaviour of interpreting script tag

We all know what <script src="/something.js"></script> does. That file is loaded in the page and the script is run.
Is there any way to override the default behaviour of interpreting <script> elements?
I want the same syntax (<script src='...'></script>) that will only get the code from something.js (probably via XHR/jQuery ajax) and pass it to a foo (...) {...} function. Then I will care what I will do with it.
To clarify the problem:
I can easily create a pseudo <script> tag alternative using:
<div data-script-src="/1.js"></div>
<div data-script-src="/2.js"></div>
<div data-script-src="/3.js"></div>
<div data-script-src="/4.js"></div>
And then in the js side I would do:
var $scripts = $("[data-script-src]")
, scriptContents = [];
(function loadInOrder (i) {
if (!$scripts[i]) { alert("Loaded"); }
$.ajax($($scripts[i]).attr("data-script-src"), function (data) {
scriptContents[i] = data;
loadInOrder(++i);
});
})(0);
But how can I replace div[data-script] with <script>? How can I force the browser NOT to load the <script> tags that have the attribute data-load="false", for example?
I think your best bet here is to use onbeforescriptexecute. This event fires right before the script executes, so you can then modify the type attribute to something other than text/javascript (thus telling the browser not to execute the contents). This will still load the data from the server.
Unfortunately, onbeforescriptexecute is only supported in FF/Opera.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script>
document.addEventListener("beforescriptexecute", function (e) {
console.log(e.target.innerHTML || e.target.src);
}, true);
</script>
<script>
console.log("12");
</script>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
Hi
</body>
</html>
The console output will be:
'console.log("12")'
'http://code.jquery.com/jquery-1.10.2.min.js'
Create Your own PHP file, which will work as a kind of a gate. Then
<?php
$file = file_get_contents(your_url);
$file = str_replace('<script', '<myscript', $file);
$file = str_replace('</script>', '</myscript>', $file);
echo $file;
?>
And then if needed add Your type of real script that will search for myscript tags and run Javascript code...
You can use div element as well (if scripts are loaded in body, and You need validation):
substitute: '<script' -> '<div data-id="my-script" '
substitute: '<script' -> '</div>'
PS. I don't know if these are Your sites or sites from internet, that You want the default behaviour to be overwritten. So always be careful of what You are "file_getting_contents" because, this will be echoed directly to Your browser.

Categories

Resources