How to implement JavaScript into PHTML [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm fairly new to PHP and also PHTML, how would I go about implementing JavaScript into PHTML? Here is the file i'm trying to implement it into, (viewer.phtml)
<?php
if ($type == "jpeg") {
$stype = "jpg";
} else {
$stype = $type;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo APP_NAME . " - $file.$stype"; ?></title>
<link rel="stylesheet" href="/site/images/assets/css/style.css">
</head>
<body>
<h1><?php echo "$file.$type"; ?></h1>
<div class="container">
<img src="/images/<?php echo "$type/$file.$stype"; ?>" alt="<?php echo "$file.$stype"; ?>">
</div>
<?php
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $start), 4);
?>
</body>
</html>

To add a script use script tag. Inject it inside your head tag , so your head might look like this
<head>
<meta charset="UTF-8">
<title><?php echo APP_NAME . " - $file.$stype"; ?></title>
<link rel="stylesheet" href="/site/images/assets/css/style.css">
<script>
//you Javascript code here
</script>
</head>
or
<head>
<meta charset="UTF-8">
<title><?php echo APP_NAME . " - $file.$stype"; ?></title>
<link rel="stylesheet" href="/site/images/assets/css/style.css">
<script type="text/javascript" src="your_js_file_location_here"></script>
</head>
hope this will help you

JavaScript can be added the same way you did your HTML.
You can either add it outside of the PHP tags
or you can use echo to output the text of your javascript.
Example 1:
<?php
//my PHP
?>
<html>
<head>
<script>alert('hello');</script>
</head>
<body>
</body>
</html>
Example 2
<html>
<head>
<script><?php echo "alert('hello');" ?></script>
</head>
<body>
</body>
</html>
Note that once the page or text is sent to the browser, javascript does not have access to the PHP variables directly without having to call back to the server through ajax.
Example
<?php
$message="hello";
?>
<html>
<head>
<script>
//this won't work right
alert('<?php $message ?>');</script>
<script>
//this will alert the value of $message at the time echo was called
alert('<?php echo $message ?>');</script>
</head>
<body>
</body>
</html>
<?php
//!!! This won't matter to the javascript alerts, even though its PHP value has changed.
$message='goodbye';
?>

Related

Trying to delete element inside iframe with javascript written in php

When i call the "elem" var in the console it finds the element i want, but only after i run in the console it deletes the element not when the page is loaded.
<html>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<head>
</head>
<link rel="stylesheet" href="../../CSS/index.css">
<body>
<div>
<?php
$page=$_GET['id'].".html";
echo '<iframe src="' .$page.'" id="'.$_GET['id'].'" frameBorder="0" width="70%" height="100%" align="left" scrolling="no" />';
echo '</iframe>';
?>
</div>
<?php
echo " <script>
var elem=document.getElementById('".$_GET['id']."').contentWindow.document.getElementById('".$id."');
elem.parentNode.removeChild(elem);
</script> ";
?>
</body>
</html>
Try with code, Hope it might help you.
document.getElementById('myframe1').contentWindow.document.getElementById('x');

Wordpress - load jQuery in head on specific page Template

I have a page template that needs jQuery loaded in the header instead of the footer.
The Theme (Divi Theme) loads jQuery in the footer by default. This causes some errors, when jQuery is loaded twice.
Is there any way I can modify <?php wp_footer(); ?> to exclude jQuery for this template?
Thanks.
Template:
<!DOCTYPE html>
<html <?php language_attributes(); ?> class="no-js">
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="<?php echo get_site_url(); ?>/cam-forms/styles/cam-forms.min.css" />
<script type="text/javascript" src="<?php echo get_site_url(); ?>/cam-forms/js/jquery.js"></script>
<script type="text/javascript" src="<?php echo get_site_url(); ?>/cam-forms/js/jquery-migrate.min.js"></script>
</head>
<body>
<?php echo do_shortcode( get_field('form') ); ?>
<?php wp_footer(); ?>
</body>
</html>
You have to add <?php wp_head(); ?> in the following place:
<!DOCTYPE html>
<html <?php language_attributes(); ?> class="no-js">
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="<?php echo get_site_url(); ?>/cam-forms/styles/cam-forms.min.css" />
<script type="text/javascript" src="<?php echo get_site_url(); ?>/cam-forms/js/jquery.js"></script>
<script type="text/javascript" src="<?php echo get_site_url(); ?>/cam-forms/js/jquery-migrate.min.js"></script>
<?php wp_head(): ?>
</head>
<body>
<?php echo do_shortcode( get_field('form') ); ?>
<?php wp_footer(); ?>
</body>
</html>
Then, in you file functions.php add this..
function theme_scripts(){
wp_register_script('fileName', get_template_directory_uri() . '/js/file.js', array( ), '1.0.0');
wp_enqueue_script('fileName');
}
add_action('init', 'theme_scripts');
Also I always suggest you to work with the minified files for CSS and JS.
add below function in function.php for add js and css file in header and remove file in footer
<?php
remove_action('wp_footer', 'wp_enqueue_scripts', 1);
add_action('wp_head', 'wp_enqueue_scripts', 5);
function mycustomscript_enqueue() {
wp_enqueue_style( 'ca-forms-min', get_template_directory_uri() . '/cam-forms/styles/cam-forms.min.css', array('ca-forms-min'));
wp_enqueue_script( 'jquery', get_stylesheet_directory_uri() . '/cam-forms/js/jquery.js', array( 'jquery' ));
wp_enqueue_script( 'jquery-migrate', get_stylesheet_directory_uri() . '/cam-forms/js/jquery-migrate.min.js', array( 'jquery-migrate' ));
}
add_action( 'wp_enqueue_scripts', 'mycustomscript_enqueue' );
?>

jQuery script stops working when integrated in a dynamic PHP file

I usually build my website's pages in .html and then, when everything works, I create the .php page for db and all the server-side stuff.
'Till now I hadn't any problem, but since when I'm trying to integrate some JS scripts in my pages, every time, the same script that in the .html sample works fine in the .php page doesn't work fine or doesn't work at all. Today I was "fighting" with the LightGallery script integrated in my gallery.php file.
I tried everyhing possible before posting this question but whitout any success; I definitely need your help!
This code in the .html page referres to the jQuery gallery and it works fine:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>...</title>
<link rel="stylesheet" type="text/css" href="css/main.css">
<link rel="stylesheet" type="text/css" href="css/gallery.css">
<link rel="stylesheet" type="text/css" href="test/css/lightGallery.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
</head>
<body>
<!-- A jQuery plugin that adds cross-browser mouse wheel support. (Optional) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.js"></script>
<script src="test/js/lightgallery.js"></script>
<!-- lightgallery plugins -->
<script src="https://cdn.jsdelivr.net/picturefill/2.3.1/picturefill.min.js"></script>
<script src="test/js/lg-thumbnail.js"></script>
<script src="test/js/lg-fullscreen.js"></script>
<script src="test/js/lg-autoplay.js"></script>
<div id="header">
....
</div>
<div id="content">
<div id="selector1">
<div class="item" data-src="img/art.jpg">
<figure>
<img src="img/urban.jpg" />
</figure>
</div>
<div class="item" data-src="img/art.jpg">
<figure>
<img src="img/urban.jpg" />
</figure>
</div>
</div>
</div>
<div id="footer">
.....
</div>
<script type="text/javascript">
$('#selector1').lightGallery({
selector: '.item'
});
</script>
</body>
</html>
Since it worked, I integrated it in this .php file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="Marco Brigonzi">
<?php
/* check URL */
$query_url = $_SERVER['QUERY_STRING'];
$pageID = substr($query_url, 6);
?>
<title>Album: "<?php $title = ucfirst($pageID);
echo $title; ?>" | Photo</title>
<link rel="stylesheet" type="text/css" href="css/main.css">
<link rel="stylesheet" type="text/css" href="css/gallery.css">
<link rel="stylesheet" type="text/css" href="script/lightgallery/css/lightGallery.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
<?php include("php/header-footer.php"); ?>
</head>
<body>
<?php include_once("php/analyticstracking.php"); ?>
<!-- jQuery version must be >= 1.8.0; -->
<!-- <script src="jquery.min.js"></script> -->
<!-- A jQuery plugin that adds cross-browser mouse wheel support. (Optional) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.js"></script>
<script src="script/lightgallery/js/lightgallery.js"></script>
<!-- lightgallery plugins -->
<script src="https://cdn.jsdelivr.net/picturefill/2.3.1/picturefill.min.js"></script>
<script src="script/lightgallery/js/lg-thumbnail.js"></script>
<script src="script/lightgallery/js/lg-fullscreen.js"></script>
<script src="script/lightgallery/js/lg-autoplay.js"></script>
<script src="script/lightgallery/js/lg-hash.js"></script>
<script src="script/lightgallery/js/lg-pager.js"></script>
<script src="script/lightgallery/js/lg-zoom.js"></script>
<?
$current = "photo";
head($current);
?>
<div id="content">
<div id="selector1">
<?php
/* check URL */
if($pageID == 'urban')
{$pageCode = '1';}
elseif($pageID == 'art')
{$pageCode = '2';}
elseif($pageID == 'street')
{$pageCode = '3';}
elseif($pageID == 'nature')
{$pageCode = '4';}
else
{echo 'Error 0';}
/* connessione */
......connection values........
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn)
{die("Connection failed: " . mysqli_connect_error());}
/* SET utf8 charset for special characters */
if (!mysqli_set_charset($conn, "utf8"))
{printf("Error loading character set utf8: %s\n", mysqli_error($conn));
exit();
}
$sql_pic = 'SELECT * FROM photos WHERE album="'.$pageCode.'" ORDER BY rating DESC';
$result_pic = mysqli_query($conn, $sql_pic);
if (mysqli_num_rows($result_pic) > 0)
{
while($row_pic = mysqli_fetch_assoc($result_pic))
{
echo '<div class="item" data-src="img/photo/'.$pageID.'/'.$row_pic["name"].'.jpg" alt="">
<figure>
<img src="img/photo/'.$pageID.'/thumb/'.$row_pic["thumb"].'.jpg" alt="">
</figure>
</div>';
}
}
else
{echo 'Error 1';}
mysqli_close($conn);
?>
</div>
</div>
<?php foot(); ?>
<script type="text/javascript">
$('#selector1').lightGallery({
selector: '.item'
});
</script>
</body>
</html>
And, of course, it stops working. I tried to put the JS scripts' calling at the end of the page but nothing changes. I've really no clue, 'cause the code is exactly the same! It's only integrated in a .php dynamic page.
[SOLVED] This time the problem was the capital letter in the CSS call: the server host renamed lightGallery.css in lightgallery.css so the CSS file was missing. Thanks everyone for the help!

Codeigniter equivalent of Zend headscript

Im trying to find out if theres any thing similar to codeigniter as there is in Zend where I can append files to a header area like CSS or Footer area like javascript. Problem is I can't find anything which means either one doesn't exist and I have to make one (which not sure how to tackle that exactly), or I am searching for the wrong thing. Or I dunno. Anyone here know something?
This is what I am usually using in my CI projects...
application/views/v_header.php
<head>
<title><?php print $this->config->item('sitename'); if(isset($title)) echo ' - '.$title; ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="generator" content="xxxxxx" />
<meta name="author" content="Matteo Mattei - www.matteomattei.com"/>
<meta name="description" content="xxxxxxxxxxxxxxx"/>
<meta name="robots" content="INDEX,FOLLOW"/>
<meta name="keywords" content="xxxxx, xxxxx, xxxxx"/>
<link rel="shortcut icon" href="<?php echo base_url(); ?>images/favicon.ico" />
<?php
if(isset($style))
{
if(is_array($style))
{
foreach($style as $s)
echo '<link rel="stylesheet" href="'.base_url().'css/'.$s.'" type="text/css" media="screen" />';
}
else
echo '<link rel="stylesheet" href="'.base_url().'css/'.$style.'" type="text/css" media="screen" />';
}
?>
<link rel="stylesheet" href="<?php echo base_url(); ?>css/style.css" type="text/css" media="screen" />
<?php
if(isset($jquery) && $jquery===TRUE)
echo '<script type="text/javascript" src="'.base_url().'js/jquery-1.7.1.min.js"></script>';
echo '<script type="text/javascript">';
echo 'var base_url="'.base_url().'";';
if(isset($js_variables))
{
foreach($js_variables as $k=>$v)
{
echo 'var '.$k.'="'.$v.'";';
}
}
echo '</script>';
if(isset($js))
{
if(is_array($js))
{
foreach($js as $j)
echo '<script type="text/javascript" src="'.base_url().'js/'.$j.'"></script>';
}
else
echo '<script type="text/javascript" src="'.base_url().'js/'.$js.'"></script>';
}
?>
</head>
<body>
In each controllwer function I can specify custom CSS files or JS files:
public function myfunc()
{
$data['jquery'] = TRUE;
$data['js'] = array(
'jquery-ui-1.8.16.custom.min.js',
'my_special.js',
'another_special.js',
);
$data['style'] = array(
'ui-lightness/jquery-ui-1.8.16.custom.css',
'my_custom.css',
);
$this->load->view('v_header',$data);
$this->load->view('v_menu',$data);
$this->load->view('v_dashboard',$data);
$this->load->view('v_footer',$data);
}

Zoom image script not working

I'm trying to get this script to work but am having some trouble.
This is my website.
I followed the instructions on the script's website and did this:
Added the reference for the script to head.
Added <script type="text/javascript">$(window).load(function() {$('body').nivoZoom();
});</script> right after the script reference in the head. Should I call the function elsewhere?
Wrapped the smaller image inside <a> tags and added the class of nivoZoom. All the links for images are working.
The problem with my website is that the script isn't working. Instead, if the smaller image is clicked it just leads to the large image address and doesn't zoom as it's suppose to.
UPDATE:
Here's my whole <head>, I don't see where I load jQuery for the second time OK, I see that it loads but I can't find where the code is:
<head>
<script type="text/javascript" src='/wp-content/themes/thefalltheme/js/example.js'></script>
<link rel="stylesheet" href="http://india.thefalljourney.com/wp-content/themes/thefalltheme/js/nivo-zoom.css" type="text/css" media="screen" />
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js?ver=3.2.1'></script>
<script src="/wp-content/themes/thefalltheme/js/jquery.nivo.zoom.pack.js"></script>
<script type="text/javascript">
$(window).load(function() {
$('body').nivoZoom();
});
</script>
<meta charset="<?php bloginfo('charset'); ?>" />
<?php if (is_search()) { ?>
<meta name="robots" content="noindex, nofollow" />
<?php } ?>
<title>
<?php
if (function_exists('is_tag') && is_tag()) {
single_tag_title("Tag Archive for ""); echo '" - '; }
elseif (is_archive()) {
wp_title(''); echo ' Archive - '; }
elseif (is_search()) {
echo 'Search for "'.wp_specialchars($s).'" - '; }
elseif (!(is_404()) && (is_single()) || (is_page())) {
wp_title(''); echo ' - '; }
elseif (is_404()) {
echo 'Not Found - '; }
if (is_home()) {
bloginfo('name'); echo ' - '; bloginfo('description'); }
else {
bloginfo('name'); }
if ($paged>1) {
echo ' - page '. $paged; }
?>
</title>
<link rel="shortcut icon" href="http://india.thefalljourney.com/wp-content/themes/thefalltheme/images/favicon.png?force=1">
<!-- <link rel="shortcut icon" href="http://india.thefalljourney.com/wp-content/themes/thefalltheme/images/favicon_blue.png?force=1">
<link rel="shortcut icon" href="http://india.thefalljourney.com/wp-content/themes/thefalltheme/images/favicon_flag_india.png?force=1"> -->
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>">
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>">
<?php if ( is_singular() ) wp_enqueue_script('comment-reply'); ?>
<?php wp_head(); ?>
</head>
UPDATE 2:
Found the additional loading, it was in the functions.php.
At the top of your page, you load jQuery + nivoZoom:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="/wp-content/themes/thefalltheme/js/jquery.nivo.zoom.pack.js" type="text/javascript"></script>
A few lines below, you load jQuery again, causing the previously made extensions to the jQuery framework to be undone:
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js?ver=3.2.1'></script>
You should include the nivo zoom script AFTER loading jQuery:
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js?ver=3.2.1'></script>
<script src="/wp-content/themes/thefalltheme/js/jquery.nivo.zoom.pack.js"></script>
Another note: Your CSS file is missing. Make sure that you also upload it.

Categories

Resources