How to set a php variable with javascript? [duplicate] - javascript

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 8 years ago.
I am going to set a php variable with javascript, the php variable.
I want to give size of browser to a php variable and then echo best css for that (a kind of responsive website by different css and not css3).
<script src="jquery-1.10.2.js"></script>
<script>
$(function(){
var size=($(document).width());
if(size>300){
<?php
$size="more";
?>
}else if(size<300){
<?php
$size="less";
?>
}
})
</script>
<?php
if($size=="more"){
echo '<link rel="stylesheet" href="index-1024.css"/>';
}else if($size=="less"){
echo '<link rel="stylesheet" href="index-less-1024.css"/>';
}
?>
With this code php variable $size is always 'less'

PHP scripts are executed at server. and Javascripts(jQuery) scripts are executed at your browser. There is no way you can set variables like that. Perhaps consider switching the css entirely in javascript:
script src="jquery-1.10.2.js"></script>
<script>
$(function(){
var size=($(document).width());
//if large screen, swap in large css
if(size>300){
$('#mystyle').attr("href", "index-1024.css");
}
})
</script>
<?php
//load small css as default
echo '<link rel="stylesheet" href="index-less-1024.css" id="mystyle"/>';
?>

Related

Turn PHP variable into Javascript variable and use that Javascript variable as an argument in a Javascript function

An input from a form in my index.php page is sent to my search.php page. This input is turned into the PHP variable $q with $_GET. How do I turn this PHP variable into a Javascript variable that is a string? Then how do I pass this string as an argument in a Javascript function in the body tag when the page loads? The onload function only works if the first parameter is a string. Here is my simplified code:
<?php
if(isset($_GET["q"])) {
$q = $_GET["q"];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="assets/js/script.js">
var q = "<?php echo $q;?>";
</script>
</head>
<body onload="return Search(*PHP variable turned into Javascript string*, otherFunction(), otherFunction2())">
<div>
Content
</div>
</body>
</html>
Javascript within your script tag 'should' be ignored if there's a src for it. However you can't have precompiled php in a js file. One option is to set the javascript variables within your php files, then separately include your js files. If your js files make use of those variables, make sure to set the variables first:
<script type="text/javascript">
var q = "<?php echo $q;?>";
</script>
<script src="assets/js/script.js"></script>
The script doesn't work because you're trying to include an external JavaScript file, while also using the same tag for inline script.
This part
<script src="assets/js/script.js">
var q = "<?php echo $q;?>";
</script>
Should look something like this
<script src="assets/js/script.js"></script>
<script>
var q = "<?php echo $q;?>";
</script>
Fully fixed code
<?php
if(isset($_GET["q"])) {
$q = $_GET["q"];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="assets/js/script.js"></script>
<script>
var q = "<?php echo $q;?>";
</script>
</head>
<body onload="return Search(q, otherFunction(), otherFunction2())">
<div>
Content
</div>
</body>
</html>
Edit: Footnote
As #dossy points out, you should avoid directly passing user input into the HTML code. Use json_encode() to avoid any malicious code or invalid input.
<script>
var q = <?php echo json_encode($q); ?>;
</script>
This is what json_encode() is for. Other answers that use the naive approach of var x = "<?php echo $var; ?>"; will break if $var contains a double quote, for example.
This is the safest way of doing this:
<script type="text/javascript">
var q = <?php echo json_encode($q); ?>;
</script>

PHP - how can I echo <script> tag with an src attribute? [duplicate]

This question already has answers here:
Script tags with src and code between script tags
(4 answers)
Closed 4 years ago.
I've looked around but couldn't find an answer to this.
How can I echo a script tag that has an src attribute?
When I try this:
echo '<script type="text/javascript" src="script.js">document.writeln(3);
</script>';
the code fails.
But when I do this and remove the src tag:
echo '<script type="text/javascript">document.writeln(3);</script>'
the code works.
what am I overlooking and how can I make the first version work?
You either include a src attribute, which references a file for the code or include the code directly in the script tag. You don't put both.
It should actually be like this:
echo '<script type="text/javascript" src="script.js"></script>';
echo '<script type="text/javascript">document.writeln(3);</script>';

Including jQuery script on wordpress template [duplicate]

This question already has answers here:
Wordpress how to use jquery and $ sign
(17 answers)
Why is my javascript file not found by wordpress? and why doesn't my javascript file refresh?
(6 answers)
Closed 5 years ago.
I have a page template which is applied to a specific page on my wordpress page. Usually for all of my other scripts i put them in my footer.php and they load from there beautifully. On this specific page though I want to load a script that only should be running on this page. So in my template i include it like this:
<?php
/**
* Template Name: Template
*/
?>
<?php get_header(); ?>
<script src="<?php echo get_template_directory_uri(); ?>/js/teacher-signup.js"></script>
<?php get_footer( ); ?>
Unfortunately when doing that I only get errors like:
Uncaught TypeError: $(...).whatever is not a function
Is there some way in Wordpress to include a couple of scripts on a specific template only? Or am I missing something?
Thanks in advance
register the script like wp recommends:
wp_register_script('your_file_name', get_template_directory_uri() . '/assets/js/some_file.js', false, null, true);
than enqueue the registered script for that specific page/template
if (is_page('page_name') ) {
wp_enqueue_script('your_file_name');
}
you can also add a conditional for the page template name if you want:
if (is_page_template("template_name.php')
You can make if conditional is_page() in certain page id / page slug for example
<?php if (is_page( 1 )) : ?>
<script src="<?php echo get_template_directory_uri(); ?>/js/teacher-signup.js"></script>
<?php endif; ?>
You can put it on your footer.php theme

how to call jquery function in php file

I'm working on a project and my problem is calling a jQuery function like this placing it in my php file. I've tried searching a lot but I'm always coming out with an error:
Function:
$(function(){
$(".panorama-view").panorama360();
});
Php file
<?php
echo '<link rel="stylesheet" href="/css/panorama360.css" rel="stylesheet" >';
echo '<script src="/js/jquery.mousewheel.min.js" ></script>';
echo ' <script src="/js/jquery.panorama360.js" ></script>';
echo '<script> $(function(){ $(\'.panorama-view\').panorama360(); }); </script>';
echo '</script>';
if(isset($_POST['upload'])) {
$image_name= $_FILES['image']['name'];
$image_type= $_FILES['image']['type'];
$image_size= $_FILES['image']['size'];
$image_tmp= $_FILES['image']['tmp_name'];
if(move_uploaded_file($image_tmp,"uploadedimg/$image_name"))
{
echo "<script type='text/javascript'>alert('File Uploaded!');</script>";
}
$folder= "uploadedimg/";
if(is_dir($folder)) {
if($handle = opendir($folder)){
while(($file= readdir($handle)) !=false){
if($file === '.' || $file === '..')
continue;
echo '<div class="panorama round" style=" width:1200px; height:500px; padding:10px ;background-color:#444; position: relative;">';
echo '<div class="panorama-view">';
echo '<div class="panorama-container">';
echo '<img src="uploadedimg/'.$file.'" data-width="4077" data-height="500" alt="Panorama" />';
echo '</div>';
echo '</div>';
echo '</div>';
}
closedir($handle);
}
}
} ?>
You get Uncaught ReferenceError: jQuery is not defined or Uncaught ReferenceError: $ is not defined error (as seen in your shared screenshot in comments under your post) because you have not included the jQuery library in your project.
Both errors are identical and pointing to the same problem as explained above.
Note that you CANNOT use panorama360 without making use of the jQuery library as it (jQuery library) is a required dependency.
To include the jQuery library in your project, you have two (2) main options; either:
You consume it from a content delivery network (CDN) by including it in your project as shown in the snippet below,
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
or,
downloading and referencing it directly from your stored location
<script src="/path/to/jquery-3.1.1.min.js"></script>
There is a last option which has to do with combining the earlier two mentioned above, using one as a graceful failover; here is the illustration:
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="path/to/jquery-3.1.1.min.js"><\/script>')</script>
(With the above, you can make use of the jQuery library in your project by consuming it from the CDN and automatically load the version on your sever should the later fail. More details here)
It's important to note that your jQuery library declaration SHOULD occur before the referencing of your panorama360 JavaScript resources; either:
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<script src="/js/jquery.mousewheel.min.js"></script>
<script src="/js/jquery.panorama360.js" ></script>
Should you chose to use PHP echo() function to handle your file inclusion, do use a single quote or escape your double quotes. ... more details here.
So, you should be doing something like this:
<?php
echo "<link rel='stylesheet' href='/css/panorama360.css'>";
echo "<script
src='https://code.jquery.com/jquery-3.1.1.min.js'
integrity='sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8='
crossorigin='anonymous'></script>";
echo "<script src='/js/jquery.mousewheel.min.js'></script>";
echo "<script src='/js/jquery.panorama360.js'></script>";
echo "<script>$(function(){ $('.panorama-view').panorama360(); });</script>";
To reference your resources without making use of PHP the raw HTML way as discussed in comment below,
<?php
// Should you want to run any PHP codes before referencing your resources,
// you may do so here.
// Remember: you MUST close this section as below this comments so as to
// mark the end of your PHP code
?>
<link rel="stylesheet" href="/css/panorama360.css">
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<script src="/js/jquery.mousewheel.min.js"></script>
<script src="/js/jquery.panorama360.js"></script>
<script>$(function(){ $('.panorama-view').panorama360(); });</script>
<?php
// Here, other PHP codes
?>

How can I use Joomlas <?php echo $this->template ?> in Javascript?

how could I use <?php echo $this->baseurl ?> or <?php echo $this->template ?> inside of an Javascript script?
Like this:
!window.jQuery && document.write(unescape('<script src="/xxx/<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/js/jquery-1.7.2.min.js" data-mce-type="text/javascript" data-mce-type="text/javascript" data-mce-type="text/javascript" data-mce-type="text/javascript">
or in a script tag which is not in the index.php
<script type="text/javascript" src="/xxx/templates/<?php echo $this->template ?>/js/plugins.js"></script>
JavaScript fundamentally cannot execute any PHP code. Remember that PHP runs on the server, generates an HTML document, and sends it back to the browser. Then JavaScript begins running. This means whatever data you want to use in JavaScript must already be on the page by the time Joomla is finished running.
If you do need to fetch additional content from Joomla, look into using AJAX requests. You could build a page that outputs $this->template, for example, and then request that page from JavaScript in the background.

Categories