Loading javascript in Code Igniter - php

For our Code Igniter application we are loading all of our javascript just before the closing body tag.
so in our controllers we have
$this->load->view('head', $this->head);
$this->load->view('main_view_for_controller', $data);
$this->load->view('foot', $this->foot);
And in the foot view we have a bunch of <script src="master.js"></script> tags.
These include
jQuery
jQuery-ui
shared-functions
Now this works great, until you think about JS used only on specific pages, or inline js.
You can't just dump your javascript anywhere in the page as it will generally use bit's and pieces of the parts you load at the bottom.
So what I do at the moment is,
I have /application/views/js/ where I will have something like login.php
login.php may contain e.g.
<script>
$(function(){
var user_id = <?php echo $this->user->get('id'); ?>;
var return = '<?php echo $return_url; ?>';
$('#login form').submit(function(){[...]});
$('#login .facebook').click(function(){[...]});
});
</script>
so in my controller I would call
$this->foot['js'][] = javascript('login', array('return_url' => '/users'));
//source of function javascript() from inside a helper
function javascript($file, $config = array()){
return $this->load->view('js/'.$file, $config, true);
}
then in my foot view after all the other files (which on the prod env are merged into one file and then minified) I have
foreach($js as $jsOut) echo $jsOut;
which simply spits out all the javascript.
Is this the best way of doing this? or is there a better way?
This just seems kind of messy...

A good idea might be to use page segments to determine what scripts to include. Rather than having to populate an array all of the time, you could define your scripts and what pages they belong too, then just check the page segments to determine what JS scripts to include. Read the documentation for the URI class here.
So in your include you'd do something like this.
<?php if ( $this->$this->uri->rsegment(2) == 'login' ): ?>
// Your login page specific scripts here
<?php endif; ?>
<?php if ( $this->$this->uri->rsegment(2) == 'home' ): ?>
// Your homepage specific scripts here
<?php endif; ?>
Replace the number 2's with whatever segment relates to the page you're on.

Related

include js library to head from inside the body and specific to only one page

I use google charts js library in only one page in my project and I have external and global head and footer. head tags are in head.php file and required js libraries are included in there. Anatomy of my pages are like this:
<?php
require('header.php');
?>
<div>my body elements of this page lie here </div>
<?php
require('footer.php');
?>
I can include google charts library in header.php. It will be loaded in every page, but I need it in only one page. So, I do not want to make the loading progress slow. How can I include that library only if I am loading this particular page? Is it possible? Thanks in advance.
Simply add a variable before you include the header, and check for that variable within header.php
<?php
//page that requires the js
$chartjs = true;
require('header.php');
?>
<div>my body elements of this page lie here </div>
<?php
require('footer.php');
?>
.
<?php
//header.php
if(isset($chartjs) && $chartjs){
//inlcude js file here
}
Alternatively, You could load it conditionally via JavaScript depending on the context of the page, I'll use jQuery here for ease of use with the Ajax side of it, so for example:
Page Body:
<div class="chart"></div>
Header.php
<script>
var $charts = $('.chart');
if ( $charts.length ) {
$.getScript("charts.js", function(){
$charts.plot(); //init.
});
}
</script>
This will delay the loading of the chart however though. Also, for reference how to load without the jQuery library, see Load scripts after page has loaded? for some good references on post-page load scripts.
Reference $.getScript
You have several options. One is what Steve recommended in his answer.
I'd like to use this in chart page:
require('header.php');
?>
<script type="text/javascript" src="chart.js"></script>
<div>my body elements of this page lie here </div>
<?php
require('footer.php');
The other is to check the $_SERVER["REQUEST_URI"], and include only in header, it this is the specified page.

Conditional php include in wp using media queries and javascript

I may be going about this all wrong, but here goes.... Im trying to use JavaScript in a WP theme file to do conditional PHP includes based on CSS media queries and pseudo-elements.
In the CSS I use a media query to check for mobile devices in portrait mode, add a hidden :after element to the body under this query with content="mobile_portrait" attribute.
I then wanted to go on the homepage template and use JavaScript like this:
var size = window.getComputedStyle(document.body,':after').getPropertyValue('content');
if (size == 'mobile_portrait') {
<?php
add_action( 'genesis_after_header', 'do_this' );
function do_this() {
require(CHILD_DIR.'/do_this.php');
}
?>
}
else {
<?php
add_action( 'genesis_after_header', 'do_the_other' );
function do_the_other() {
require(CHILD_DIR.'/do_the_other.php');
}
?>
}
It seems like WP is skipping the JavaScript and parsing the PHP because if I take out the else it just loads do_this.php whether the Java check returns true or false, if I leave the else in, it breaks the site :(
Ideas about what im doing wrong? or a better way to load PHP files based on media queries?
Thanks in advance
PHP and Javascript cannot be used interchangeably like you are trying to do.
PHP is the renderer, it is building the output (building the Javascript)
The PHP will be run, regardless of where they are put inside a Javascript conditional like you have, as the Javascript conditionals have no bearing on them being executed.
==
Now to add a solution:
Maybe use the javascript like you have setup simply redirect to the phpfile you want to run for a given view:
var size = window.getComputedStyle(document.body,':after').getPropertyValue('content');
if (size == 'mobile_portrait') {
window.location = '<?= CHILD_DIR.'/do_this.php'; ?>';
}
else {
window.location = '<?= CHILD_DIR.'/do_the_other.php'; ?>';
}
So have different pages that do the necessary includes based on the media query

Using .php parsed as javascript source, how to wrap javascript code between php brackets using conditionals

Currently i'm working on a project which requires dynamical content parsed using some simple javascript functions, which i need to load depending on which 'view' is currently using a given user.
I'm having issues using something like this on a .js or .php file:
** .php file that calls javascript.
<script type="text/javascript" src="*.js/.php" />
** .js file
<?php header(Content-type: 'application/javascript'); ?>
alert('this shows correctly);
<?php if(isset($_REQUEST['view']) {
if($_REQUEST['view']=='private_view') { ?>
var xname = <?php echo $_SESSION['x']; ?>
//Array stuff filled from MySQL queries.
<?php } ?>
<?php if($_REQUEST['view']=='public_view') { ?>
var other_variable = <?php echo $xxx; ?>
$(element).functions();
<?php } ?>
The php code i'm using works correctly, already tested it. I'm also convinced that there are other ways to work this around, like using different files and choosing them with a conditional right on .php where I define script call, but i'm so curious about why this isn't working.
I'm used to work like this wrapping HTML content between brackets, to hide or show depending on given conditions.
The output of this will be only alert call, no PHP error/warning/notification,
I can't seem to find a correct way to do this, have been searching for a while but only find how to parse .js as php modifying .htaccess file.
You should simply rename the .js file to a .php file.

How to create a php header with different css and js?

Quick and should be simple question, but i cant find the answer!!! So im trying to make a universal header called header.php. Now the only problem is that some pages have 5 css style sheets while others have only 2. And some pages have 5 js links in the header while some only have 1. How do i account for this variability in css and js links in the header? Am i suppose to use if statments? Variables? Thanks!
Consider combining resources to single ones. This will minimize HTTP requests which is a good practice.
Instead of creating a static header.php, create a function to include javascript files dynamically. For example, you need only jquery & jquery ui js references for page1, so you call
include_js('jquery', 'jquery-ui')
where include_js is your function which will insert respective JS files.
Similarly, in page2, you need assume you need jquery & jquery.fancybox
include_js('jquery', 'jquery.fancybox')
You should be using a setup like this. Of course, you might want to make it so that the styles are included from your view and not your controller. Can't give a better answer without knowing your setup.
In your controller
$styles_for_layout = array();
$scripts_for_layout = array();
//and whenever you need to include a script in for your particular view
$scripts_for_layout[] = 'script_for_page.js';
$styles_for_layout [] = 'style_for_page.css';
headerp.php
<?php if(!empty($styles_for_layout))?>
<?php foreach ($styles_for_layoutas $style) : ?>
<link rel='stylesheet' href='<?php echo $style ?>'>
<?php endforeach; ?>
<?php endif; ?>
<?php if(!empty($scripts_for_layout))?>
<?php foreach ($scripts_for_layout as $script) : ?>
<script type='text/javascript' src='<?php echo $script ?>'>
<?php endforeach; ?>
<?php endif; ?>
Loading all the CSS and JS file in every page won't matter much as after a first load, they will be cached and not retrieved again.
Therefore, you could just bundle them and not worry if you really need a particular file in the current page or not.

Having includes with variables in two places at once

I have a small situaton here. I'm building a custom CMS for one of my websites.
Below is the code for the main index page:
<?php
require("includes/config.php");
include("includes/header.php");
if(empty($_GET['page'])) {
include('pages/home.php');
} else {
if(!empty($_GET['page'])){
$app = mysqli_real_escape_string($db,$_GET['page']);
$content = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM pages_content WHERE htmltitle = '$app'")) or die(mysqli_error($db));
$title = $content['title'];
$metakeywords = $content['htmlkeywords'];
$metadesc = $content['htmldesc'];
?>
<h1><?php echo $content['title']; ?></h1><hr /><br />
<div id="content"><?php echo $content['content']; ?></div>
<? } else { include('includes/error/404.php');} }
include('includes/footer.php'); ?>
The file, includes/header.php contains code to echo variables, such as, page title and meta stuff.
The issue is that when the include("includes/header.php"); is where it is, outside of the if conditions, it will not echo the varables, obviously, however, I can't put the include in the if condition otherwise, the home page, which does not require any url variables will show without these conditions.
What do I do?
You can't really write code like this for too long. It's ok to for start, but you will soon realize it's hard to maintain. The usual way is to split it into a few steps.
First check input and determine on which page are you
If you know you are on the homepage, include something like includes/templates/homepage.php
Otherwise try to load the page from the database
If it worked, include includes/templates/page.php
Otherwise include includes/templates/404.php
Each of the files in includes/templates will output the whole page, i.e. they all include the header, do something and include the footer. You can use for example Smarty templates instead of PHP files, which will make the approach obvious.
Once you have this, you can split the code even more. Instead of loading the page directly from index.php, include another file which defines a function like load_page($name) and returns the page details.
Then a few more changes and you realize you are using the MVC approach. :) The functions that load data from the database are your Models, the Smary templates are Views and the PHP files that put them together are Controllers.

Categories