Let's say I have some html file like this:
<body>
<div></div>
</body>
Given that I have referenced jQuery correctly, and I have a .js file like:
$(document).ready(function(){
$('div').html(4);
});
That will output 4 when the html is viewed in a browser. Why does it not show anything when I do this?
$(document).ready(function(){
$('div').html(<?php echo 4; ?>);
});
Well a .js file isn't a PHP file. You can alternatively rename your .js file into blah.js.php where you can execute blocks of PHP inside that file, but still have the file act like jQuery when you include it in your page.
You should try to keep the dynamic content on the page and leave the Javascript file static. This will allow the browser to cache your Javascript. So, here is how you can get your dynamic values to your static Javascript.
Your page should look like this:
<html>
<body>
<div></div>
<script>
var myNumber = <?php echo 4; ?>;
</script>
</body>
</html>
And your Javascript file should look like this:
$(document).ready(function(){
$("div").html(myNumber);
});
Related
I'd like advice on the best way to include dynamic js variables. There are certain js variables which come from the server, similar to:
var user_preferences = [<?php //declare some type of array here;?>];
Obviously, you can't run PHP in a *.js file (though I suppose you could with Apache and a .htaccess directive), and besides I believe you don't want dynamic content in a *.js file because the whole idea is for the browser to cache the code.
The total set of these variables (such as AJAX url locations, user settings) is actually pretty small. I really would prefer not to declare them all on a page, but instead include them somewhere, but how would I do that given that they are dynamic?
As guys in comments said, you can run php in js files, just rename it.
Example of JS file, named generated_data.php:
function pero( miki ) {
miki.innerHTML = "<?php echo $_SERVER['DOCUMENT_ROOT']; ?>";
console.log("ext");
}
now, let us add this to html:
<html>
<head>
<script src="generated_data.php"></script>
</head>
<body>
<div id="test"></div>
<script>
pero( document.getElementById("test") );
</script>
</body>
</html>
You're close. All this in one file
<?php
$someCoolVar = "[1,2,3,4,5]";
// ...
?>
//.....
<script>
var myVar1 = <?=$someCoolVar;?>; // myVar1 = [1,2,3,4,5];
// ...
</script>
I found on stackoverflow how to use a php variable in jquery, but on my test page, it simply isn't working:
$('#q').keyup(function(e) {
var test = "<?php echo 'test123'; ?>";
alert(test);
});
The code above outputs "" literally in the box where I want it to say "test123". I tried using single quotes instead of double, other small changes ... Didn't get it to work. Am I missing something?
The code above sits in a .js file which is linked in a .php page, which is (again) linked in my index.php file via require_once.
You should not use PHP in javascript files (.js). Javascript and PHP are different languages. PHP works on the server-side and Javascript on the client-side.
You have to put this code in your <head> under the jquery.js file, like this:
<script type="text/javascript" src="link-to-jquery-file.js"></script>
<script type="text/javascript">
$('#q').keyup(function(e) {
var test = "<?php echo 'test123'; ?>";
alert(test);
});
</script>
Also make sure your file extension ends with .php
There is also an advanced solution for this, and that would be using the header() function. Save as javascript.php or someting Example:
<?php
header("Content-Type: text/javascript");
?>
$('#q').keyup(function(e) {
var test = "<?php echo 'test123'; ?>";
alert(test);
});
Then attach the file in your <head> like this:
<script type="text/javascript" src="javascript.php"></script>
Goodluck!
I've created a PHP page to upload a file to the server.
I've created a HTML page with javascript that parses a file on the server.I'd like to upload the file and after a successful upload directly open the HTML page and use the (uploaded) file name as parameter for my javascript.How to combine these two. I can't get it working.
Umm, there's very little information here, but one way would be to render out your html with a hidden field where the value of the field was the filename. Then you could call getElementById or whatever method you use to find selectors to read that in, then use that in your javascript.
<html>
<body>
<span id="submittedFilename" style="display: none"><%php $filename %></span>
</body>
</html>
<script>
var filename = $('submittedFilename").html();
</script>
Another option would be to set a variable into your rendered php (html) page, and then use that in your javascript.
<script>
var filename = <%php $filename %>;
</script>
================ EDIT ==========================
<%php // This is your processing script
... Your processing logic ...
// After processing, add a variable called filename to session.
session_start();
$_SESSION['filename'] = $filename;
header('Location: /newPhpScript.php');
%>
-- Then your new php script could look something like this:
<%php session_start() %>
<html>
<body>
<script>
// if using jQuery
var filename = $('#filename').text();
// else use this
var filename = document.getElementById('filename').innerHTML;
</script>
<span id="filename" style="display: none"><%php echo $_SESSION['filename'] %></span>
</body>
</html>
This seems like an odd problem. Maybe it's also the wrong approach. But I have to do this:
there are a few menu items on a page
the content for each page is stored in some .phtml files
when the page loads the default content is displayed (using require)
all other content should be loaded too and should be stored in a JavaScript-array
when a user clicks a link, the content is swapped
The problem is:
AJAX should not be used
all content can't be appended in the beginning, for the good old SEO
All parts are easy, except for: How do I get the content into a JavaScript array. Something like content.push('<?php print require 'page.phtml'; ?>'); won't work of course, because it will return a multi line string, which does not work with JavaScript. All ideas are welcome. Maybe I'm overlooking something very simple.
<script>
<?php
ob_start();
require 'page.phtml';
$contents = ob_get_clean();
echo "var content = ".json_encode($contents);
?>
</script>
if there is no php code in your page.phtml file you can make it even easier
<script>
<?php
echo "var content = ".json_encode(file_get_contents('page.phtml'));
?>
</script>
obviously you can use it in this way too:
echo "content.push(".json_encode($contents).");";
why not function
<?php
function json_require($filepath) {
ob_start();
require($filepath);
return json_encode(ob_get_clean());
}
?>
...
content.push(<?=json_require('page_1.phtml');?>);
content.push(<?=json_require('page_2.phtml');?>);
content.push(<?=json_require('page_3.phtml');?>);
content.push(<?=json_require('page_4.phtml');?>);
you can use hidden divs than using js array, At the end of the your page so they wont effect the seo. Then use these divs id to swap your content.
I hope you are using jQuery if not this can be done even with simple js.
let me elaborate
<script>
function shouldBeCalledAtSomeEvent(page_id)
{
var html = $('#'+page_id+').html();
$('#idOfYourTargetElem').html(html)
}
</script>
<!-- end of your main file -->
<div style="display:none" id="page_1">
include('page_1.phtml');
</div>
<div style="display:none" id="page_2">
include('page_2.phtml');
</div>
<div style="display:none" id="page_3">
include('page_3.phtml');
</div>
If you can't use ajax and you're worried about seo, I recommend you use a modified version of #rupesh answer: store the html in script tags so that they can be accessed by js and not be read by crawlers :
<script type="text/hidden-menu" class="hidden_menu" >
include('page_1.phtml');
</script>
<script type="text/hidden-menu" class="hidden_menu" >
include('page_2.phtml');
</script>
<script type="text/hidden-menu" class="hidden_menu" >
include('page_3.phtml');
</script>
And then you can easily build your array in js :
var content = [],
contentNodes = document.getElementsByClassName('hidden_menu'),
i=0;
for(;i<contentNodes.length;i++)
content.push(contentNodes[i].innerHTML);
And voila: you have your content array that holds the html sent from php without using ajax and without affecting seo.
I have a JavaScript file which has a hard coded BASEURL variable, this value is then used by other functions in the file.
I would like for this url value to be set dynamically so that I don't need to manually change it for different installs. Is it possible to insert a PHP variable value into a JavaScript file?
Rather than try to mix PHP into javascript files, here's what I do in the HTML template:
<head>
<script>
var BASEURL = "<?php echo base_url(); ?>";
</script>
<script src="/path/to/my_script1.js"></script>
<script src="/path/to/my_script2.js"></script>
</head>
This sets the variable and allows all your embedded scripts to access it. base_url() would be replaced by whatever method you use to fetch the base url with PHP.
Suppose you have a JS file written on the fly by PHP; file1.php
<?php
header('Content-Type: application/javascript');
$var = $_GET['var1'];
echo "jsvar = ".$var.";";
?>
The client-side source code of file1.php?var1=10 will then be
jsvar=10;
There exists several ways:
Load the baseurl via AJAX, but maybe this is to slow, maybe you need it earlier.
let the javascript file running through the php parser. Then you could use inline echos.
The most convenient and easiest way, is to make a <script>var baseurl = '...';</script> in the html/php output of your page.
You will need to make your file a php file, not a js file. From there you can include any PHP tags in the file to work your dynamic magic. The key to make this whole thing work is in the headers, which you will need to set like so:
<?php
Header("content-type: application/x-javascript");
echo 'var js_var = ' . $php_var;
?>
alert (js_var);
This technique can be used to for CSS files as well.
Heredoc worked for me today:
<?php
echo <<<ANYNAME
<script LANGUAGE="JavaScript" type="text/javascript">
<!--
// code ...
var myLatlng = new google.maps.LatLng($lat, $lon);
// code cont. ...
//-->
</script>
ANYNAME;
?>
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
php variable in html no other way then: <?php echo $var; ?>