I have a PHP variable that I am declaring upon loading the page, and want to use it in a JavaScript/jQuery function that loads upon a button click.
I have the following on my index.php page:
// Creating a random name for a file and creating it. Working properly.
$fname = substr(md5(rand()), 0, 7);
$file = fopen("temp/" .$fname, 'w');
And when I click a button, the following JavaScript function should run:
//Use the generated filename in the JavaScript function
var fname = <?php echo $fname; ?>;
var fileName = "temp/" + fname;
My understanding is that the PHP variable is outside of the scope of the JavaScript function, since I believe this is the way it should be done.
Can you please help with this?
PHP generates a page and presents it to a browser. As far as the browser is concerned, by the time the page is received, PHP is finished. So to answer your question, that should work, since PHP will essentially just spit out the text on to the page, which will act as normal. That is, unless I am terribly misinformed.
The "scope" of a PHP variable is long gone by the time Javascript gets to run, so that isn't really an issue.
Try do this. in a php file of course.
var fname = '<?php echo $fname; ?>';
I think you need an extension on your filename:
$extension = ".txt";
$fname = substr(md5(rand()), 0, 7).$extension;
$file = fopen("temp/" .$fname, 'w');
The problem is the missing apostroph like anant kumar singh mentioned.
I tested the following code in a webpage:
<?php
$fname = substr(md5(rand()), 0, 7);
$file = fopen("temp/" .$fname, 'w');
?>
<html>
<head
</head>
<body>
<script>
var fname = "<?php echo $fname; ?>";
var fileName = "temp/" + fname;
</script>
</body>
</html>
Related
Below is my jQuery Code:
<script>
$(document).on('click','.quickview', function(){
var **image** = $(this).attr('image');
var testimage = document.getElementById('quickimage');
testimage.src= "<?= base_url().'assets/product_images/'.image.".png"?>";
});
</script>
I want to use this image value to the src attr of img which is in a modal, what is the best way can please help? I will be very thankful to you.
You can't use JavaScript variables in PHP, since PHP runs on the server and finishes before the page is sent to the browser.
But you don't need to use the JS variable in PHP. You can do the concatenation in JavaScript.
testimage.src= <?= json_encode(base_url()) ?> + `assets/product_images/${image}.png`;
Just like in demo of kirby
<?php foreach(page('projects')->children()->visible()->limit(3) as $project): ?>
I want to make dynamic limit of records.
How can i do that?
I have tried JavaScript but it not worked.
Here is JavaScript code that no worked
<script>
var p1 = 3;
function load()
{
p1=p1+3;
}
</script>
<?php
$number="<script>document.write(p1)</script>";
// echo $number;
<?php foreach(page('projects')->children()->visible()->limit($number) as $project): ?>
//Code Here
<?php endforeach ?>
<div class="text-center">LOAD MORE</div>
suggest me if anyone has done it.
You can't, at least not in this way.
Think of when and where your code is getting executed. PHP is executed by the server, before the browser even receives the page. JavaScript is executed by the browser, after the page is done loading.
You can either have a separate script that generates what you need from your number, and pass that as a GET or POST value to the script via an AJAX request, or generate the number you need in PHP.
So in case of an AJAX request you'd have your PHP script doing something like:
<?php
$number = $_GET['number'];
foreach (page('projects')->children()->visible()->limit($number) as $project) {
echo .....
}
?>
and your JavaScript would call that script via an AJAX request and put the resulting HTML into your page, with something like:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
document.getElementById("container").innerHTML = xht.responseText;
}
xhr.open("GET", "script.php?number=" + p1, true);
xhr.send();
Update: Found a solution! Using chrome developer tools, I've found that the problem is hardcoding src files in /Applications/blahblah. It's looking for the files in localhost/Applications/blahblah. For now, I've copied the .js files it needed in a subdirectory to /Library/WebServer/Documents/ (where localhost seems to start from on my machine) and coded a path to there. Thanks for the help!
Newbie to PHP here. Can't find my answer with some thorough googling and lots of trying to debug myself.
I'm doing everything locally on my own machine.
I have a PHP class which builds an string that makes up an html page in its entirety, then returns it. My index.php script creates an instance of this class and calls the function that returns the html, and echos it the return. When I execute this class, the page comes up blank (using chrome as a browser). When I "view source" on the blank page, I see exactly the html script I had intended to view.
If I copy and paste that html script into a new file, blahblah.html and load blahblah.html directly with chrome, it works just fine.
Possible subtlety: the html string includes a javascript function which pulls from a hard-coded src directory on my machine.
Thanks for the help! Let me know what more information I might provide that could help.
EDIT: Here's the code:
index.php:
<?php
function __autoload($class_name)
{
$source = '/Path/To/src/' . $class_name . '.php';
if (file_exists($source)) require $source;
else throw new Exception('class "' . $class_name . '" source file not found. Failed to autoload...');
}
$myweb=new GenHCSplineIrregTime();
echo $myweb->genWeb();
?>
GenHCSplineIrregTime.php:
<?php
class GenHCSplineIrregTime
{
public function __construct()
{
;
}
public function __destruct()
{
;
}
public function genWeb()
{
return $this->genEntireHTMLFile();
}
private function genEntireHTMLFile()
{
$cont="";
// $cont = $cont . "<!DOCTYPE HTML>\n";
$cont = $cont . "<HTML>\n<head>\n";
$cont = $cont . "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n";
$cont = $cont . "<title>This is my title</title>\n";
$cont = $cont . "<script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js\"></script>\n";
$cont = $cont . "<style type=\"text/css\">\n\${demo.css}\n</style>\n";
$cont = $cont . "<script type=\"text/javascript\">\n";
$cont = $cont . "\$(function () {\n\n$('#container').highcharts({\nchart: {\ntype: 'spline'\n},\n title: {\ntext: 'BATTERY SHIT'\n},\nsubtitle: {\ntext: 'Irregular time data in Highcharts JS'\n},\n";
$cont= $cont . "xAxis: {\ntype: 'datetime',\ndateTimeLabelFormats: {\nmonth: '%e. %b',\nyear: '%b'\n},\ntitle: {\ntext: 'Date'\n}\n},\n";
$cont= $cont . "yAxis: {\ntitle: {\ntext: 'Snow depth (m)'\n},\nmin: 0\n},\ntooltip: {\nheaderFormat: '<b>{series.name}</b><br>',\npointFormat: '{point.x:%e. %b}: {point.y:.2f} m'\n},\n";
//data starts here
$cont= $cont . "series: [{\nname: 'Winter 2007-2008',\ndata: [\n";
$cont= $cont . "[Date.UTC(1970, 9, 27), 0 ],\n";
$cont= $cont . "[Date.UTC(1970, 10, 10), 0.6 ],\n";
$cont= $cont . "[Date.UTC(1970, 10, 18), 0.7 ]\n]\n}]\n";
$cont= $cont . "});\n});\n";
$cont= $cont . "</script>\n</head>\n<body>\n";
$cont= $cont . "<script src=\"/Applications/BasicSoftware/Highcharts-4.0.3/js/highcharts.js\"></script>\n";
$cont= $cont . "<script src=\"/Applications/BasicSoftware/Highcharts-4.0.3/js/modules/exporting.js\"></script>\n";
$cont= $cont . "<div id=\"container\" style=\"min-width: 310px; height: 400px; margin: 0 auto\"></div>\n";
$cont= $cont . "</body>\n</html>\n";
return $cont;
}
private function fetchData()
{
$data="";
return $data;
}
}
?>
This happens because PHP is a server-sided scripting language, not a client-sided one like HTML. It needs a server to run on. To have a web server on your computer, you'll need software like WampServer or XAMPP. Once you have these installed, you can use PHP.
UPDATE: Your code outputs nothing because the GenHCSplineIrregTime class is not imported correctly. You will need to use the require or include (or require_once, include_once, depends on what you need) statements to add GenHCSplineIrregTime.php, but not the way you did it. You did what some old manuals show:
//foo.php
<?php
class foo {
public function __construct() {
echo "hi";
}
}
?>
//index.php
<?php
function __autoload($classname) {
$filename = "./". $classname .".php";
include_once($filename);
}
$obj = new foo();
?>
Problem is, what's $classname? The code is incomplete; it will just load nothing, really, or some irrelevant file. That's why, instead, you'll almost always see:
//index.php
<?php
require 'foo.php';
$obj = new foo();
?>
UPDATE 2: I am glad that your problem was resolved but for next time, pay special attention to the title of the page, which was changed (because everything but the Javascript part of the HTML worked). Hence, it wasn't a completely blank page as you implied (i.e. no HTML compiled).
if you have your html code in a string, let say $str, all you need is to print the content of the string just like this :
$str "<h1> Hello world ! </h1>";
echo $str;
If your html code is inside another page , all you need to do is to load the content of your page inside a string and print it :
$str = file_get_contents("path_to/blahblah.html");
echo $str;
PHP only runs on a server.
Download XAMPP and run apache server.
After you downloaded and installed it, go to the xampp folder, and to htdocs folder and put your php file in there.
And navigate to where your php file is located, for example: localhost:/index.php.
Then your php code should run properly.
Well if you're viewing the HTML in the source then you know that the HTML string is being printed. So maybe you're doing something with headers? Possibly Chrome doesn't expect to receive HTML content when you print it from PHP, but when you take the same content and put it into a file with .html extension it's a no-brainer, so it renders it automatically. Try opening up the Chrome's dev tools, reload the page and look under 'network' to see what headers you're receiving.
If you are in fact printing the html string, as you've verified in the 'source' received by the client (chrome) then you know your php code was evaluated. Given that as true, and without trying to guess at what is going on with the js script, that is the only thing I can think of.
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.
i'm trying to get Magento BaseUrl through javascript in head.phtml file, and then use it in jquery.hello-lightbox.min file, where i need the baseUrl to get some images.
Here's what i have in head.phtml file:
<?php $baseUrl = $this->getBaseUrl() ; ?>
<script type="text/javascript">
var baseUrl = <?php echo $baseUrl ; ?>
function getBaseUrl(baseUrl)
</script>
Then in /js/jquery.hello-lightbox.min i have:
(function($){
function getBaseUrl(baseurl)
{
var domain = baseurl
}
var urrl = 'http://'+domain+'/skin/frontend/default/customtheme/images/lightbox/';
$.fn.lightBox=function(settings)settings=jQuery.extend({overlayBgColor:'#000',overlayOpacity:0.8,fixedNavigation:false,imageLoading: urrl+'lightbox-ico-loading.gif',imageBtnPrev:urrl+'lightbox-btn-prev.gif', . . . . . . . . . .
But this doesn't work. In fact it seems like i can't even pass the php variable $baseUrl to var baseUrl in head.phtml
Do you have any ideas?
There are syntax errors in your main code. I think what you want is to define a function that returns the base URL like so:
<?php $baseUrl = $this->getBaseUrl() ; ?>
<script type="text/javascript">
function getBaseUrl() { return '<?php echo $baseUrl; ?>'; }
</script>
then use it in JavaScript: (get rid of the function getBaseUrl(baseurl) ... stuff there)
var urrl = 'http://'+getBaseUrl()+'/skin/frontend/default/customtheme/images/lightbox/';
Try to put quotes around the JS var you're setting via the php echo:
var baseUrl = '<?php echo $baseUrl ; ?>'
You can call base url via these simple steps throughout the store in every javascript / php file.
Open your theme's page/html/head.phtml and add following code in the HEAD tag in the last line:
<script type="text/javascript">
var BASE_URL = '<?php echo Mage::getBaseUrl(); ?>';
</script>
Now you can use BASE_URL variable in every javascript code in your theme files to get magento base url in javascript.
If you don't want to use inline Javascript, you can always just add it as an attribute to a div or something along those lines.
For example, I'll often add a html element like this:
<div class="my-class" data-storeurl="<?php echo Mage::getBaseUrl(); ?>">
....
</div>
And then in my Javascript (jQuery in this case), I'll just add something like:
var current_store = $('.store-redirect').attr('data-storeurl');
It's handy for AJAX calls where you want to run the call on the correct store's url.
EDIT:
Javascript won't pass variables between files like that. You don't need to use PHP in this case, just do this:
var urrl = 'http://'+window.location.host+'/skin/frontend/default/customtheme/images/lightbox/';
Magento : Get Base Url , Skin Url , Media Url , Js Url , Store Url and Current Url:
Get Base Url :Mage::getBaseUrl();
Get Skin Url :Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);
Unsecure Skin Url :$this->getSkinUrl('images/imagename.jpg');
Secure Skin Url :$this->getSkinUrl('images/imagename.gif', array('_secure'=>true));
Get Media Url :Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
Get Js Url :Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);
Get Store Url :Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
Get Current Url :Mage::helper('core/url')->getCurrentUrl();
Get Url in cms pages or static blocks:
Get Base Url :{{store url=""}}
Get Skin Url :{{skin url='images/imagename.jpg'}}
Get Media Url `:{{media url='/imagename.jpg'}}
Get Store Url :{{store url='mypage.html'}}