Include JavaScript files to the document head with php - javascript

I'm creating a blog where I included header.php(Header, included in every page). Header contains a section where all the scripts (Scripts that will need in every pages) will be included.
header.php
<!DOCTYPE html>
<html>
<head>
<!-- Scripts Section -->
<script src="example01.js"></script>
<script src="example02.js"></script>
<title>Demo</title>
</head>
<body>
<p>Blog</p>
But in a specific page, I've to include a specific script (file.js named).
index.php
<?php
include('header.php');
importjs('file.js'); /* Any Function To Import JavaScript*/
?>
If I include the JavaScript file here then it'll be included in body not the scripts section in the header. I don't know how to create that function. So please tell me how to create that function. create function in header.php and please first include the header before using function.
Thank You

I think, you should to write your line code like this example:
<?php int a; ?>
<script type="text/javascript" src="file.js" />
<?php int b; ?>

Related

Can't use php variables defined in another file

I have three php files, one defines a constant, the other has the html markup and includes a php file wigh renders js content. the third is the php file rendering the js content. the code is as shown below.
the first file named "config.php" :
<?php
define('TESTVAR','test variable');
?>
the second file named "main.php" :
<?php
require_once ('config.php');
?>
<!doctype html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<script type="text/javascript" src="script.php"></script>
</body>
</html>
the third file named "script.php" :
alert(<?php echo TESTVAR ?>);
this is what gets loaded as script.php:
<b>Notice</b>: Use of undefined constant TESTVAR - assumed 'TESTVAR' in <b>C:\xampp\htdocs\trials\testphpinjs\script.php</b> on line <b>2</b><br />
TESTVAR);
it's not that php is not being rendered, if i change the script.php to
alert(<?php echo '\'testing'. 'php' . 'echo\'' ?>);
it works perfectly and the loaded script can be viewed from developer tools as
alert('testingphpecho');
the only problem I have is that I cannot access the variables in pages required or included before
Using <script type="text/javascript" src="script.php"></script>, the browser will issue a new request to load script.php directly. Since PHP is stateless, that request will not be handled in the same context as whatever processing goes on in main.php.
If you want to use the variables/constants defined in config.php within script.php, you will have to load it in there:
<?php require_once('config.php'); ?>
alert("<?php echo TESTVAR; ?>");
Note that I've added quotation marks, since TEST_VAR is a string value in your example.
If your Javascript code relies on more than just config.php and its behavior depends on pre-processing that's done in main.php, it might be better to load it as an inline script instead:
<?php
require_once ('config.php');
?>
<!doctype html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<script type="text/javascript">
<?php include('script.php'); ?>
</script>
</body>
</html>
This way, PHP is loading the script.php file within the same context as main.php, and all constants and variables defined there will (should) be available for use by the code that's outputting your Javascript.

Create an external file for side menu

How do I create an external file for my side menu?
<a class="active" href="C.html" style="font-size: 1.1em;font-weight: 900;">C Programming</a>
C++
C#
Go
Java
JavaScript
PHP
Python
Ruby
Swift
Currently I have these kind of links in every file and the code is just getting too much. Is there a way to create an external file for the menu items?
I tried this but the problem is class="active". I want to highlight a menu item when my menu item is in index.php
I Know how to achieve this when my menu is in each individual HTML file but how do I do that when it's in external PHP file ?
Index.php
<html>
<head>
<link rel="stylesheet" type="text/css" href="CSS/Tags.css">
<link rel="stylesheet" type="text/css" href="CSS/Nav.css">
<link rel="stylesheet" type="text/css" href="CSS/Card.css">
<link rel="stylesheet" type="text/css" href="CSS/Buttons.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="sidenav">
<h1>&nbspOthers</h1>
MS Excel
MS PowerPoint
MS Word
WordPress
</div>
</body>
</html>
Main file
<?php include('index.html'); ?>
You should NOT use javascript to include your menu .
you can use PHP to simply include your menu ( but i sugget header ) file to your page :
<?php include('/template/header.html'); ?>
or you can use pre processors like Gulp :
##include('./template/header.html')
var fileinclude = require('gulp-file-include'),
gulp = require('gulp');
gulp.task('fileinclude', function() {
gulp.src(['index.html'])
.pipe(fileinclude({
prefix: '##',
basepath: '#file'
}))
.pipe(gulp.dest('./'));
});
or Pug or Grunt and ......
About your problem in comments . lets say you are in your main folder and you have this 3 files :
index.php
header.html
homepage.html
footer.html
index.php should be like this :
<?php
include('header.html');
include('hompage.html');
include('footer.html');
?>
and then in your browsers you should open index.php .
** don't use index.html and index.php in the same time .
if it didn't work . you should get error in your index.php file .
when your code works . i suggest you to use readfile() instead of include . if your another files are just html and not have any php codes in it .
As pointed out by Abolfazl Ghaemi :
You should NOT use javascript to include your menu . you can use PHP to simply include your menu ( but i sugget header ) file to your page :
<?php include('/template/header.html'); ?>
The Gulp/Grunt solution is fine but I'll stick with the <?php include(); ?> solution for your problem.
Does the hosting machine speak PHP ?
If browsers can read HTML just fine to give you a webpage, they can't read PHP. Instead, PHP need to be executed by something on the hosting machine and you will need a PHP interpreter for that like Apache.
If you didn't already, I strongly recommend you to install it or even a full AMP stack.
PHP in HTML files won't work
You need to make sure your file using PHP instructions are .php files. Otherwise, the code in your <?php ?> tag (the PHP code) won't be interpreted at all.
Make sure your main file is a .php file.
Are you calling the correct file ?
Also, you need to be sure the file name you are including is correct. The content as shown in your question is
Main file
<?php include('index.html'); ?>
but your file is actually index.php not index.html.
HTML is prettier with CSS
If you want to "highlight" the item with active class, you will need CSS. You can quickly add CSS in your file with a <style> tag. See the example below.
<ul>
<li>Not highlighted</li>
<li>Still not highlighted</li>
<li class="active">Highlighted ! Spotlight's on me baby !</li>
<li>Not highlighted</li>
</ul>
<style>
.active {
color: red;
font-weight: bold;
}
</style>

dynamic php header file with dynamic .js and .css include

I would like to do a dynamic include of my .css and .js file within the head tags in my header.php that depend on the current .php file that is open. So it will save some loading time if the .js or .css file is not needed for the current .php page.
So I thought I check the current url if it includes (strpos) a spicific string (e.g. "mycollection.php") and if yes echo the <link> and <script> tags to include the .css or .js files for the current, opened php file. But it seems to be hard to do a clean script this way. Does anyone has a clean, short and better solution for this problem?
Thank you in advance!
Try code below :
<!DOCTYPE html>
<html>
<head>
<?php
$get_url=$_SERVER['REQUEST_URI'];
$get_extension=explode('/',$get_url);
$get_extension_php=end($get_extension);
if($get_extension_php=='mycollection.php')
{
echo '<link href="your.css"/>';
echo '<script src="your.js"></script>';
}
?>
</head>
<body>
</body>
</html>
Hope it helps you
I used it before but not in the link but before the include of the header and it was like that
if (!isset($css){ echo "<link></link>;}
and at the header of the page if I didn't need to include the css file I just declare the variable $css = ''; and here we go hope this what you were asking for

How Can JQuery be embedded in the <body> and </body> Tags in Joomla 3.1?

I've added this code below to my default.php file in joomla 3.1.
<?php
JHtml::_('jquery.framework');
JFactory::getDocument()->addScript(JURI::root().'template/mytemplate/js/jquery.min.js');
?>
This only embeds the script inside the head tags.
Is there a way i can make it appear in the body tag?
You can simply put
?>
<script type="text/javascript" src="<?php echo JURI::root();?>templates/<?php echo $app->getTemplate();?>/js/jquery.min.js" />
Into your template index.php
or
?>
<script type="text/javascript" src="<?php echo JURI::root();?>templates/mytemplate/js/jquery.min.js" />
into any template override
I can't see the benefit of doing this though at all.
As mentioned in my comment on the other question, you can't import jQuery in the <body> tag using the JHtml() or JFactory method. These methods add the script to the <head> tag automatically.
The only way you can achieve what you want is to use <script> tags, however please see how I have done it:
<?php
// load jQuery, if not loaded before
if(!JFactory::getApplication()->get('jquery')){
JFactory::getApplication()->set('jquery',true);
?>
<script>
jQuery.noConflict();
</script>
<script src="<?php echo JUri::root(). 'template/mytemplate/js/jquery.min.js'; ?>"></script>
<?php
}
?>
This basically checks to see if jQuery is being imported already and if not, then it imports it. Add this code to the index.php in your template folder.
If you see the following in your index.php:
JHtml::_('jquery.framework');
then remove it.
Please bare in mind that this is not a recommended method however it's the only way that I know of to import it after the <body> tag.
Also note that if you ever update your template, then your changes will be lost

Yii and jquery and javascript inclusion...confused

Crossposting from http://www.yiiframework.com/forum/index.php/topic/37313-confused-about-jquery-and-script-inclusion-handling/ but sometimes people answer here more rapidly...
I am totally confused about Yii's handling of jquery and other javascript file inclusion.
This was working:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#Event_recuring_nature, #Event_venue, #Event_expected_attendance, #Event_age_group, #Event_state, #Event_gender, #Event_ethnicity, #Event_exclusivity, #Package_cash_product_sponsorships, #Event_vanue_signature, #Event_logo_on_step_and_repeat, #Event_inclusion_in_press, #Event_ad_space, #Event_inclusion_in_event_materials, #Package_category_exclusivity, #logo_on_signature, #Event_proposed_events_included, #Event_dependant_on_sponsorship, #Event_sponsorship_type, #Event_attendee_professions, #Event_attendee_income').yaselect();
});
</script>
<script type="text/javascript" src="/js/libs/jquery-ui-datetimepicker.js"></script>
<script type="text/javascript" src="/js/event_create.js"></script>
<script type="text/javascript" src="/js/slider.js"></script>
<script type="text/javascript" src="/js/other_social.js"></script>
<script type="text/javascript" src="/js/package.js"></script>
while this (which supposedly would be better?) does not:
<?php
Yii::app()->clientScript->registerScript('create-script', "
$(function() {
$('body').css('overflow-x','hidden');
$('#Event_recuring_nature, #Event_venue, #Event_expected_attendance, #Event_age_group, #Event_state, #Event_gender, #Event_ethnicity, #Event_exclusivity, #Package_cash_product_sponsorships, #Event_vanue_signature, #Event_logo_on_step_and_repeat, #Event_inclusion_in_press, #Event_ad_space, #Event_inclusion_in_event_materials, #Package_category_exclusivity, #logo_on_signature, #Event_proposed_events_included, #Event_dependant_on_sponsorship, #Event_sponsorship_type, #Event_attendee_professions, #Event_attendee_income').yaselect();
});
");
?>
<?php Yii::app()->clientScript->registerScriptFile($this->assetsBase.'/js/libs/jquery-ui-datetimepicker.js'); ?>
<?php Yii::app()->clientScript->registerScriptFile($this->assetsBase.'/js/event_create.js'); ?>
<?php Yii::app()->clientScript->registerScriptFile($this->assetsBase.'/js/slider.js'); ?>
<?php Yii::app()->clientScript->registerScriptFile($this->assetsBase.'/js/other_social.js'); ?>
<?php Yii::app()->clientScript->registerScriptFile($this->assetsBase.'/js/package.js'); ?>
I had the directory
<app_dir>/js/ for all javascript and created
<app_dir>/protected/assets/js as suggested in a post on the yii forum for registerScriptFile (which supposedly handles script inclusion nicely).
I ended up having of course duplicated files and I am cleaning up.
The layout has this in the header:
<?php Yii::app()->clientScript->registerCoreScript('jquery')?>
<?php Yii::app()->clientScript->registerScriptFile($this->assetsBase.'/js/libs/jquery-ui-1.8.20.custom.min.js')?>
<?php Yii::app()->clientScript->registerScriptFile($this->assetsBase.'/js/libs/jquery.yaselect.min.js')?>
<?php Yii::app()->clientScript->registerScriptFile($this->assetsBase.'/js/script.js')?>
and I have this in config/main.php:
// application components
'components'=>array(
'clientScript'=>array(
'packages'=>array(
'jquery'=>array(
'baseUrl'=>Yii::app()->request->baseUrl . '/js/libs/',
'js'=>array('jquery-1.7.2.min.js')
)
)
),
(I know that baseUrl is now pointing to /js, but trying with
'baseUrl'=>Yii::app()->basePath . '/assets/js/libs'
also did NOT load jquery at all!!!
PLEASE HELP! I am new to Yii and am loosing my mind on this. Thank you.
EDIT: This is what the code generates:
<script type="text/javascript" src="/js/libs/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="/assets/ab20866e/jquery.yiiactiveform.js"></script>
<script type="text/javascript" src="/assets/2dfe5520/js/libs/jquery-ui-datetimepicker.js"></script>
<script type="text/javascript" src="/assets/2dfe5520/js/event_create.js"></script>
<script type="text/javascript" src="/assets/2dfe5520/js/slider.js"></script>
<script type="text/javascript" src="/assets/2dfe5520/js/other_social.js"></script>
<script type="text/javascript" src="/assets/2dfe5520/js/package.js"></script>
<script type="text/javascript" src="/assets/2dfe5520/js/libs/jquery-ui-1.8.20.custom.min.js"></script>
<script type="text/javascript" src="/assets/2dfe5520/js/libs/jquery.yaselect.min.js"></script>
<script type="text/javascript" src="/assets/2dfe5520/js/script.js"></script>
To me, the second line, /assets/ab20866e/jquery.yiiactiveform.js, looks suspicious as having a different asset id...
While I don't have your layout file in front of me, it would appear that your layout has $content before the script file registrations.
Because of this, the scripts in your view are loaded, then the scripts in the template. When this happens, the datetimepicker is being loaded, but reports errors as jquery-ui hasn't been loaded yet. Make sure that your template has the scripts loading before $content.
Alternatively, you could force scripts that are loaded in your view to be in the body, as opposed to the head by specifying a position argument, e.g.:
<?php Yii::app()->clientScript->registerScriptFile(Yii::app()->request->baseUrl . '/js/libs/jquery-ui-datetimepicker.js', CClientScript::POS_BEGIN); ?>
Another thing to consider is forcing Yii to load jQuery from the start like so:
cs()->registerCoreScript('jquery');
You can also load jQuery UI like so:
cs()->registerCoreScript('jquery.ui');
I find this solves a lot of registerScriptFile POS_BEGIN/POS_HEAD issues when loading other jQuery libraries and files (as in ernies answer)

Categories