Codeigniter: How to include javascript files - javascript

Hello I just started working with CodeIgniter framework. My current directory structure is
Demo(Project name)
+System
+Application
-Controllers
demo.php
+Model
-Views
view_demo.php
-Js
ajax.js
jquery.js
Please tell me how to include .js files in view_demo.php.
Thanks
Raj

You need to use the base_url() to include the javascript file in your VIEW.
So, in the view_demo.php file:
<script type="text/javascript" src="<?=base_url()?>js/jquery.js" ></script>
<script type="text/javascript" src="<?=base_url()?>js/ajax.js" ></script>
You will need the URL helper loaded. To load the helper you need to put on your demo.php controller:
$this->load->helper('url');
You can also autoload on \config\autoload.php on the helpers array.
More info about base_url(): http://www.codeigniter.com/user_guide/helpers/url_helper.html#base_url
https://codeigniter.com/user_guide/general/styleguide.html#short-open-tags

You wouldn't include JS files within the PHP, they would be output as script tags within the HTML you produce which you may be producing as output from the PHP script.
As far as I know, there is no built in CodeIginiter function to include this output like there is for CSS using the link_tag() function provided by CI. I've added a function called script_tag() to the system/helpers/html_helper.php file from CI. The function is:
if ( ! function_exists('script_tag')) {
function script_tag($src = '', $language = 'javascript', $type = 'text/javascript', $index_page = FALSE)
{
$CI =& get_instance();
$script = '<scr'.'ipt';
if (is_array($src)) {
foreach ($src as $k=>$v) {
if ($k == 'src' AND strpos($v, '://') === FALSE) {
if ($index_page === TRUE) {
$script .= ' src="'.$CI->config->site_url($v).'"';
}
else {
$script .= ' src="'.$CI->config->slash_item('base_url').$v.'"';
}
}
else {
$script .= "$k=\"$v\"";
}
}
$script .= "></scr"."ipt>\n";
}
else {
if ( strpos($src, '://') !== FALSE) {
$script .= ' src="'.$src.'" ';
}
elseif ($index_page === TRUE) {
$script .= ' src="'.$CI->config->site_url($src).'" ';
}
else {
$script .= ' src="'.$CI->config->slash_item('base_url').$src.'" ';
}
$script .= 'language="'.$language.'" type="'.$type.'"';
$script .= ' /></scr'.'ipt>'."\n";
}
return $script;
}
}
Then in your PHP code you can do:
echo script_tag('content/js/jquery-1.4.2.js');

I store my javascript in a subdirectory of my view folder so the file path is relative to the view being called and I omit the base_url().
Another technique I adopted was to define an array of scripts to include in my controller, then loop through the array in my view to include them. This allows me to include specialty js functions only when needed.
$data['scripts to load'] = array('edit.js', 'menu.js', 'contact.js');
$this->load->view('myview');
Then in the view
<?php foreach($scripts_to_load as $script):?>
<script type='text/javascript' src = 'my_js/<?php echo $script;?>'>
<?php endforeach;?>
If you have script files that get loaded on every page, you can hard code them in your footer view like is described in the other answers.

The $data variable sometimes may be lost if you have nested views and you don't pass it as an argument to the children/nested views.
I found a simple solution that is working very smoothly to me:
In your current view file you setup your script like this:
$this->scripts[] = '/js/myscript.js';
at your footer or {whatever.php} file you insert this code:
<?php
if(isset($this->scripts))
foreach($this->scripts as $script) :
?>
<script src="my_asset_path/js/<?=$script;?>"></script>
<?endforeach;?>
If you need only a pice of javascript code, you can always use anonymous functions like this:
<?php
$this->RenderScript[] = function() {
?>
<script>
console.log('myjavascript code snippet');
</script>
<?}?>
and at the bottom:
<?php
if(isset($this->RenderScript))
foreach($this->RenderScript as $script) {
$script();
}
?>

Just use the standard:
<script src="/path/to/file.js" type="text/javascript" charset="utf-8"></script>
inside your view! (Not inside the PHP tags, of course.) I don't think the CodeIgniter HTML helper has any functions that you could use as an alternative to writing out the HTML yourself.

Check out Phil Sturgeon's CodeIgniter Template Library. We use a modified version of it at work.

Related

How to pass data JSON string from PHP to external javascript

I have a php page that loads a JSON object string from a text file. I want to send the object string to an external javascript file which will eventually use it to update html displayed from the php page. Unfortunately I've had trouble getting the string to the external javascript.
I've been trying to follow the approach outlined by Afzal Ahmad here
Pass Php Arrays to External Javascript File
but I get no results
The php:
<?php
session_start();
echo 'Hello ' . $_SESSION['first'] . '<br>';
loadUserData();
displayPage();
function loadUserData(){
$userString = 'userdata/'.$_SESSION['email'].'.txt';
echo $userString;
$user = file_get_contents($userString);
}
function displayPage(){
/*html stuff here*/
}
?>
<script type="text/javascript">var userObj = <?php echo json_encode($user); ?>;</script>
<script type="text/javascript" src="scripts/index.js"></script>
The javascript:
console.log(userObj);
Your loadUserData function isn't returning anything.
You should remove the echo $userString; and add a return $user after the file_get_contents.
And you should change the loadUserData(); to $user = loadUserData();
That happens because you haven't declared $user in the function loadUserData as a global variable.
To fix the issue, you'll have to use the global keyword:
function loadUserData() {
global $user;
$userString = 'userdata/'.$_SESSION['email'].'.txt';
echo $userString;
$user = file_get_contents($userString);
}

How can I use PHP inside a wordpress site to find a hashed bundle.js file and insert the appropriate file name into the script tag?

So, I've never written php until today, and I'm trying to implement a cache breaking system on a wordpress site that has some React components living inside it. So inside of the footer-home.php file I have this:
</div> <?php // close #app ?>
</main>
<div class="container footer">
<div class="row">
<div class="col-sm-12">
<div id="instagram"></div>
</div>
</div>
<?php get_footer('shared') ?>
</div>
</div><?php //close container ?>
<?php
function grab_hashed_bundle_script() {
$path = '/client/';
$fileName = null;
$dirJS = new DirectoryIterator($path);
foreach ($dirJS as $file) {
if (pathinfo($file, PATHINFO_EXTENSION) === 'js') {
$fileName = basename($file);
break;
}
}
return $fileName;
}
$bundle_js = grab_hashed_bundle_script();
?>
<script src="/client/<?php echo $bundle_js ?>"></script>
<?php wp_footer(); ?>
</body>
</html>
I know this is ugly AF and hacky, so if anyone can point out a better way to do this, I'm all ears.
The reason I need to do this is I'm having webpack add a random 6-digit hash to the bundle.js filename(as in bundle-123456.js) every time we run a new build. Previously, we just had a regular script tag in this footer file like so:
<script src=/client/bundle.js"></script> but clients' browsers would end up caching bundle.js even after we had updated it requiring customers to have to empty their cache in order to get the new .js files.
Any help is greatly appreciated.
Also, I'm not trying to cache bust with a param as suggested in the comment. I'm trying to bust based on the random hash that I'm having webpack insert into the name of the bundle.js file upon building.
This is the solution one of my co-workers came up with:
Inside of functions.php:
/**
* Grab Hashed Bundle Files
*/
function enqueue_hashed_bundle_files() {
// soooo gross. would love to know of a cleaner way.
$build_dir = get_theme_root() . '/../../../client/build/';
$all_files = scandir($build_dir);
$css_files = array();
$js_files = array();
foreach( $all_files as $file ){
$pathinfo = pathinfo($file);
switch( $pathinfo['extension'] ){
case 'js':
array_push($js_files, $file);
break;
case 'css':
array_push($css_files, $file);
break;
default:
break;
}
}
// now that we have the filenames, we can access them directly with the
// absolute url
$base_url = get_option('siteurl') . '/client/';
wp_enqueue_script( 'bundlejs', $base_url . $js_files[0], array(), null, true );
wp_enqueue_style( 'bundlecss', $base_url . $css_files[0], array(), null );
}
Change your request for the js file to have a query param instead of a random string in the filename.
See this post. The browser shouldn't cache it with a query string.

How to create alert function in php?

i want insert user in db mysql, i have a controller php, im validate if user exist in db through a function, then if or not exist i want show alert function an redirect to php page, for that im using:
<?php
if(dao::existUser($user)) {
echo "<script type=\"text/javascript\">\n";
echo "alert('user exist!');\n";
echo "window.location = ('../insertUser.php');\n";
echo "</script>";
}
this function works!! but
i want to encapsulate the function in a method to later call it
example:
<?php
class Utils {
static function responseText($message, $url) {
echo "<script type=\"text/javascript\">\n";
echo "alert('"+$message+"');\n";
echo "window.location = ('"+$url+"');\n";
echo "</script>";
}
}
then, in my controller:
<?php
if(dao::existUser($user)) {
Utils::responseText("user exist",'../insertUser.php');
}
but not work, and after call responseText, my page goes blank
I don't know what is wrong ( likely a quoting issue ), but I would suggest using a HEREDOC style for this and return the text not output the HTML from the class by itself. Latter it could be hard to track where this output is coming from by looking just in the class that calls it. By doing echo Utills::.. you'll be able to easily see it's outputting something, whiteout having to look into what the class does.
So like this.
<?php
class Utils {
static function responseText($message, $url) {
return <<<HTML
<script type="text/javascript">
alert('$message');
window.location = '$url';
</script>
HTML; //nothing can go here no space ( before or after ) and not even this comment, nothing but HTML; litterally
}
}
echo Utils::responseText("user exist",'../insertUser.php');
HEREDOCs are a way of doing a text block without using any quotes, beware of the note i put in comments... In this case it makes the Javascript string so much more simple when you don't have to manage quote usage.
Another suggestion for this class if it is to be a collection of static methods, you can make it where it can't be instantiated ( created using new class() ) Like this
<?php
class Utils {
private function __construct(){} //no instantion
private function __clone(){} //no cloning
This way you don't accidentally do $U = new Utils(); $U->responseText(..) It's a little thing but it will insure all the methods of this class stay static. It's just a design thing I like to do, on singletons and static classes
UPDATE your issue is you are using the + to concat in PHP where you should be using the . The + is good for Javascript not so much for PHP
And the way you have it with " double quotes concat is unnecessary, instead of
echo "alert('"+$message+"');\n";
Try
echo "alert('$message');\n";
If i understand you properly bind javascript to php.
<?php
$script = '<script type="text/javascript">';
$script .= 'function showAlert(){';
$script .= 'alert("Hello World.");';
$script .= '}';
$script .= '</script>';
echo $script;
?>
Than after page has loaded you can call it !
<script type="text/javascript">
window.onload = function () {
showAlert();
}
</script>

Add JavaScript function to wordpress theme

A plugin developer who developed a comments-plugin that I use has instructed me to add the following JavaScript:
function WPACLoadMoreComments() {
window.WPACLoadMoreCount = window.WPACLoadMoreCount || 1;
var url = (new Uri(location.href)).replaceQueryParam('WPACTake', window.WPACLoadMoreCount * 20).toString();
if (WPAC.LoadComments(url, {updateUrl: false})) {
window.WPACLoadMoreCount++;
}
}
I assume he meant to put it in functions.php but the site doesn't load when I insert this code. I tried to inset it at the end, I tried to wrap it with
<?php
the function...
?>
How do I do that correctly?
You need to add the code to a javascript file and enqueue it in functions.php, or echo it via an action hook.
There's a section about including JavaScript right in the codex that's worth a read.
add below code into your functions.php file
function comment_script(){
$html = "<script type='text/javascript'>
function WPACLoadMoreComments() {
window.WPACLoadMoreCount = window.WPACLoadMoreCount || 1;
var url = (new Uri(location.href)).replaceQueryParam('WPACTake', window.WPACLoadMoreCount * 20).toString();
if (WPAC.LoadComments(url, {updateUrl: false})) {
window.WPACLoadMoreCount++;
}
}
</script>";
echo $html;
}
add_action('wp_footer','comment_script');
This is a Javascript function, not a PHP function. This means that you need to do the following:
<?php
// Your existing PHP code here
?>
<script>
function WPACLoadMoreComments() {
window.WPACLoadMoreCount = window.WPACLoadMoreCount || 1;
var url = (new Uri(location.href)).replaceQueryParam('WPACTake', window.WPACLoadMoreCount * 20).toString();
if (WPAC.LoadComments(url, {updateUrl: false})) {
window.WPACLoadMoreCount++;
}
}
</script>
<?php
//Your remaining PHP code
?>
Another possibility is to do it this way:
<?php
echo "<script>";
echo " function WPACLoadMoreComments() {";
echo " window.WPACLoadMoreCount = window.WPACLoadMoreCount || 1;";
echo "var url = (new Uri(location.href)).replaceQueryParam('WPACTake', window.WPACLoadMoreCount * 20).toString();"
echo " if (WPAC.LoadComments(url, {updateUrl: false})) {";
echo " window.WPACLoadMoreCount++;";
echo " }";
echo "}";
echo "</script>";
?>
The reason we're doing it this way is that Javascript is not executed on the server but on the user's browser (client side). Thus, there is no need to put the Javascript in <?php ?> tags, because you do not want it to be executed as PHP code. Since it will be executed by the browser, this means you need this code to appear in the HTML document loaded by the browser, and hence you should use echo or write it within <script> tags outside the <?php ?>
Performance-wise, it is always better to put Javascript code at the end of your page. This is to make sure that any possible lags, caused by the JS code while a user's browser is loading your page, do not affect the rendering of the page.
Put it in the functions.php or footer.php file somewhere outside <?php ?> and wrap it into <script type="text/javascript">Your function here...</script>

Class Not Found Error in PHP

I am a rookie PHP and MongoDB developer.
I have created a PHP web project with an HTML page that contains an 'Add' button. The name of the page is awards.html. The awards.html file contains its counterpart JavaScript file, awards.js. A code is executed in this js file when the Add button is clicked. This code sends an AJAX call to a PHP class elsewhere in the project named, example.php which contains code to execute a function called, clickFunction() in an Awards.php file, which returns a JSON array to the awards.html page.
The source code of my files is given as follows:
Awards.html
<div class = "divbottom">
<div id="divAddAward">
<button class="btn" onclick="onrequest();">Add</button>
</div>
</div>
awards.js
function onrequest() {
$("#divAddAward").load('branding/dataaccess/example.php'); //The full path of the example.php file in the web root
alert('Test');
$.post(
'branding/dataaccess/example.php'
).success(function(resp) {
json = $.parseJSON(resp);
alert(json);
});
}
example.php
<?php
foreach (glob("App/branding/data/*.php") as $filename) {
include $filename;
}
$class = new Awards();
$method = $class->clickFunction();
echo json_encode($method);
Awards.php
<?php
class Awards extends Mongo_db {
//put your code here
public function __construct() {
parent::__construct();
}
public function clickFunction() {
$array = array(
'status' => '1'
);
return $array;
}
}
The problem here is that the program is throwing me an error in example.php, Class 'Awards' not found, despite adding the for loop to include all the files. The Awards.php file is located in App/branding/data/ path and example.php is located in App/branding/dataaccess/ path.
Can anyone please tell me where exactly am I going wrong? Replies at the earliest will be highly appreciated. Thank you in advance.
My guess: as you said, example.php is located in App/branding/dataaccess/, so when you do your loop you're actually searching for files in App/branding/dataccess/App/branding/data which doesn't exist so nothing is included.
Try this:
foreach (glob("../data/*.php") as $filename) {
include $filename;
}
Update example.php to
<?php
foreach (glob('../data/*.{php}', GLOB_BRACE) as $filename) {
//Echo out each included file to make sure it's included
echo $filename . '<br />';
include $filename;
}
$class = new Awards();
$method = $class->clickFunction();
echo json_encode($method);
hmm.. try to use spl_autoload_register(); to include or require all files at once on example.php
spl_autoload_register(function($class){
require_once '../data/' . $class . '.php';
});

Categories