loaded js works different to hardcoded - javascript

I have the following script that works perfect.
<script type="text/javascript">
$(document).ready(function() {
php_test();
});
</script>
<script type="text/javascript">
function php_test() {
alert('<?php echo(DIR); ?>myfile');
}
</script>
The output is as expected:
http://localhost/mvc_framework/myfile
when I put the function php_test in a file lets say ‘php_test.js’ and bind it to my footer it executes with this output:
<?php echo(DIR); ?>myfile
Any explanation? Im confused…

The way you asked the question makes it confusing. It is possible to make PHP run on all types of files on your server with a bit of Apache tweaking. My solution will make your JS files be processed by the PHP interpreter.
What you need to do is create a .htaccess file if you are using Apache. I am going to assume you are. Then you add this line into it:
AddType application/x-httpd-php .php .js
The above code will force the PHP interpreter to run on all the formats listed in the command. You can also add .htm or even .css if you need PHP to do something with those files on the server side.
Refer to this question here for a previous solution to similar question > Using .htaccess to make all .html pages to run as .php files?
Or you can just store a whole bunch of variables from the PHP end on the page as Javascript variables like this example from one of my projects:
<script type="text/javascript">
var trackFilterFlag = null;
<?php
echo "trackFilterFlag = \"". $displayedPageType ."\";\r\n";
?>
var trackFilterCategory = null;
<?php
if(strcmp($displayedPageType, "mood") === 0 || strcmp($displayedPageType, "genre") === 0) {
echo "trackFilterCategory = \"". $filterCategory ."\";\r\n";
}
?>
var sortingTracksBy = null;
<?php
if( isset($chosenSortFlag) && strlen($chosenSortFlag) > 3 && !($defaultSort) ) {
echo "sortingTracksBy = \"". $chosenSortFlag ."\";\r\n";
}
?>
</script>
Of course I was still a novice when I wrote that code, it's possible to make it much neater and just make PHP echo the whole thing, but you understand what I mean :)

Related

Is there a way to create and modify HTML and Javascript files dynamically?

I have a project whose requirements have been consistently expanding. At first, it was fine because I could hard code most of it. However, I find that I am making different versions of the same type of forms and programming specific JS files to go along with them. Is there a way to dynamically create an HTML and JS file? So, maybe I could write a function or something that reads requirements from a text files, and from that, build an HTML file, a JavaScript file, and modify other JavaScript files within the directory. For example:
Say I have a JS file named main.js
/* I hold all the basic requirements and functions for every form*/
var blueForm = ...
var redForm = ...
There currently exists HTML files named blueForm.html and redForm.html.
I want to add a function to main.js such that:
function createNewForm(requirements){
. . .
createHTML();
createJS();
modifyMain(this); /* as in this file (main.js) */
. . .
if(successful){ return 0; }
return 1;
}
Now main.js should have been modified like:
var blueForm = ...
var redForm = ...
var greenForm = ...
And now there exists HTML files named blueForm.html, redForm.html, and greenForm.html.
The answer is yes. The most accessible way of doing this is using php, most commonly implemented through a Linux / Apache / MySQL / PHP stack (LAMP). HTML and JS be easily injected into a file your browser reads as html.
Here's a sample.php file:
<html>
<body>
<?php
echo "Hello World";
echo "<script>";
$myvar = 1;
if ($myvar==1) {
echo "function dosomethingjavascripty() {";
echo "console.log('doing it');";
echo "}";
}
echo "</script>";
?>
</html>
</body>

How to write JSON code from PHP in JavaScript file

This is my employeeshift.js code and I can't figure out how to do a PHP code in a JavaScript file
This is my code inside the employeeshift.js but my var inorno is null
$(document).ready(function(){
var inorno= "<?php echo json_encode($inOrOut ); ?>";
if(inorno=="0"){
$('.Sales1').hide();
}else{
$('.Sales1').show();
}
});
Rename your js file to php ....or past js code to php file then do like below
<?php
//some of your main php file code ..........
?>
<script type="text//javascript">
$(document).ready(function(){
var inorno= "<?php echo json_encode($inOrOut ); ?>";
if(inorno=="0"){
$('.Sales1').hide();
}else{
$('.Sales1').show();
}
});
</script>
Your JS file is probably NOT parsed as PHP script, unless you changed some server config. One way would be to rename it to employeeshift.js.php
if this is your JS file than var value will always be null, you can assign value to a var only when the file is php and you are adding this in script tag
You can't (and probably shouldn't, even if you could) write PHP into a JavaScript file. PHP on your server doesn't "know" that it should execute any PHP code you've placed there. An alternative would be to put the JavaScript, surrounded by <script></script> tags, in a PHP file, and then your could should work.

changing a js file location only when the source-code is showed

i'm trying to change a js file location when a visitor shows the source-code
, depending on that :
javascript functions don't work when the visitor shows the source-code
.
my idea is creating a file , put a javascript code to delete the file , in this situation the file won't be deleted if someone showed the source-code :
$check="$ip-$views-$id";
fopen("$check.txt","w"); //CREATING A FILE
// DELETING THE FILE ABOVE BY JAVASCRIPT , IT WON'T BE DELETED IF SOMEONE ENTERED VIA THE SOURCE-CODE MODE
?>
<div id="countno"></div>
<script type="text/javascript">
$('#countno').load('del.php?name=<?echo $check;?>&location=' + ' #countno');
</script>
<?
if (file_exists("$check.txt")) { //IF SOMEONE SHOWED THE SOURCE CODE
$new_location="fake_location.js";
}
else{
$new_location=$old_location;
}
?>
<script src="<?echo $new_location;?>"></script>
the problem now , is that the file_exists php function shows that the file still exists even though it was already deleted by the javascript code .
the file_exists function was executed before the javascript code !
any help / solution to make that php function check the file after that javascript code ? i know it's kinda impossible but it worth it !
What you are describing is not possible. php is a server side language while javascript is a client side language. Thus, the PHP on your page will always execute before the Javascript on your page executes. There is no way to make your Javascript execute first when you have it this way.
Instead, what you could do is to separate the PHP and Javascript. Have your file_exists check in another page. e.g. check.php.
if (file_exists("$check.txt")) {
echo "fake_location.js";
} else {
echo $old_location;
}
Then use an ajax call to make a request to check.php, and load your other script depending on what check.php outputs.
<script>
$.ajax({
method: "GET",
url: "check.php"
})
.done(function(script) {
$("#check").attr("src", script);
});
</script>
<script id="check"></script>
However, if your goal is to prevent people from figuring out where your javascript is located, it is not possible. Most browsers nowadays can inspect the HTML as it changes. They can see the loaded script without having to load the source separately.

Calling Javascript function in an external file through php file?

Javascript code (In another file in the same directory):
function js(str)
{
alert(str);
}
PHP code(in current file):
<?php
echo '<script type="text/javascript" src="C:\xampp2\htdocs\ARD\call_jsfunc_diff_page.js"> </script>';
echo '<script>js("hello!!")</script>';
?>
I have checked on many links on the internet, i think i'm doing the right way, but the javascript function js(str) doesn't get called !!
Can somebody help me please ??
Before you edited the question: You called the function js but you are trying to call the func function.
Access to local hard disks is also problematic. Use a relative URI and access the .js over HTTP instead.

Getting PHP variable in Javascript code

I'm trying to use PHP variables in Javascript but I couldn't. After over 2000 lines of writing different JS functions I was fine avoiding that but now I really needed it. I'm a bit lost on all the ways to go about this but nothing really worked. Here is my sequence:
index.html file:
...
<script src="myfunctions.js" />
....
myfunctions.js file:
....
function test() {
var x = <?php echo $_conf['user_id'];?>
console.log(x);
}
I was trying to rename the .js file into .php file and add
header("Content-type: text/javascript");
at the beginning - that didn't work. I was trying to make .htaccess file with
AddType application/x-httpd-php .js
But that didn't work either. I'm probably missing just a tiny thing. I just need someone fresh and bright to point it out.
You can do something like this within your JS code.
var php_var = "<?php echo $_conf['user_id'];?>"
Your javascript file should be named as "javascript.php" (just put the name you want, the only important thing is the .php
You have an index.php
Write in your index.php
include("javascript.php");
Then in your javascript.php
<script>
function test(){
var variable = "<? echo $conf['user_id'] ?>";
alert(variable);
}
<script>
PS: Yo don't need any header.
Since you're doing this via a <script> tag, your PHP script MUST output valid Javascript code, as if you'd literally type your variable assignment in manually. That means doing something like:
HTML/JS:
<script src="myscript.php"></script>
PHP:
<?php
$myvar = 'foo';
?>
var myvar = <?php echo json_encode($myvar); ?>;
Which in the end, will produce somethign that will function exactly as if you'd manually typed in the following:
<script>
var myvar = 'foo';
</script>
Note the use of json_encode(). Using this ensures that whatever you're outputting from PHP will become syntactically valid Javascript.
You're not assigning PHP value to a Javascript variable. Try:
var v = "<?php echo $_conf['user_id'];?>";
index.html
..
<script src="myfunctions.js.php" />
...
myfunctions.js.php
<?php
header('Content-Type: text/javascript');
...
?>
var val = <?php echo json_encode($val); ?>;
...
Other possible solution is to assign server-side data to attributes in html and read them in javascript. For example index.html could contain something like this:
<div id="user-profile" data-user-id="<?php echo $conf['user_id']; ?>"></div>
and in js file you can get them while necessary(example with jQuery):
var userID = $('#user-profile').attr('data-user-id');
Of course you should adjust your server-side settings to process html files.

Categories