CodeIgniter and Javascript/Jquery Library - php

As title said, I'm trying to figure out how to use javascript and jquery libraries on CI.
Following instruction in the docs, I load the library in my controller:
$this->load->library('javascript');
Then, I define the location of the jQuery file (jquery.min.js) in the config.php:
$config['javascript_location'] = 'http://localhost/ci/assets/js/jquery/');
After that, I open the view file and put in these two lines:
<?php echo $library_src;?>
<?php echo $script_head;?>
First error comes up here: Undefined variable $library_src and $script_head (don't understand where I have to set them)
Anyway, I've commented these lines and continue with jquery lib, by loading it in my controller with:
$this->load->library('jquery');
Next error: Unable to load the requested class: jquery. (it seems that it can't find the lib, what i messed up?)
Checking on system folder it looks all files are in place:
system/libraries/Javascript.php
system/libraries/javascript/Jquery.php
Thanks in advance for your help!

Put the code in the config.php like this:
$config['javascript_location'] = 'js/jquery/jquery.js';
$config['javascript_ajax_img'] = 'images/ajax-loader.gif';
In your controller file (e.g. controllers/sample.php) type this codes:
function __construct()
{
parent::__construct();
$this->load->library('javascript');
}
function index()
{
$data['library_src'] = $this->jquery->script();
$data['script_head'] = $this->jquery->_compile();
$this->load->view('sampleview', $data);
}
In your view file (e.g. views/sampleview.php) type this codes:
<?php echo $library_src;?>
<?php echo $script_head;?>
This works for me. I hope it works for you too. XD

It is important to note that this Driver is marked as experimental so I wouldn't rely on it.
Also, personally I think it's asking for confusion and headaches to try and directly mix server-side portions of your applications with client side portions.
To use javascript in your views, I would just start out by loading them like this...
<script type="text/javascript" src="<?= base_url() ?>path/to/jquery.js"></script>

Because this driver is experimental the documentation isn't quite there yet. But I was able to find a solution.
First, the documentation has an error in it. Unless you change the core Javascript library (not suggested) the reference variable is not $script_head but in fact$script_foot.
Second, once you've finished making your calls, it seems you need to run
$this->javascript->external();
and
$this->javascript->compile();
These functions set the $library_src and $script_foot variables.
To put it all together, in your controller you would have:
class Some_Controller extends CI_Controller {
public function index()
{
$this->javascript->click('#button', "alert('Hello!');");
$this->javascript->external();
$this->javascript->compile();
$this->load->view('index');
}
}
In your view you would have
<html>
<head>
<?php echo $library_src; ?>
<?php echo $script_foot; ?>

Although CI first looks for system folder, you can also try putting your libs in the these folders:
application/libraries/Javascript.php
application/libraries/javascript/Jquery.php

Not sure why you have to load your js file via controller and then echoing it in your view. You can just load ur js file using HTML tags directly in your view. Passing data from controller and echoing it in view is mostly used when your variable's value is dynamic/ needs to be loaded from databases etc.

As we know on the user guide, first, it was an experimental but working. Thr first step is open your config file under application/config/config.php .
Put the following line :
// path to JS directory you want to use, I recommended to put the .js file under 'root app/js/yourfile.js'
$config['javascript_location'] = 'js/yourfile.js';
Second step is open your controller, within constructor method, put the following code :
// Load javascript class
$this->load->library('javascript');
$this->load->library('javascript/jquery'); // if u want to use jquery
Then, still in controller file within index method :
$data['library_src'] = $this->jquery->script(); // Because I refer to use jquery I don't test to use $this->javascript->script().
Then open your view file and put the following code within tag head :
<?php echo $library_src; ?>
That way is working for me, let's try it.

Use:
$this->load->library('javascript/jquery');
instead of:
$this->load->library('jquery');
This will load your jQuery library.

I had the same problem, and found :
<?php $this->load->library('javascript'); ?>
<?php $this->load->library('javascript/jquery'); ?>
on https://ellislab.com/forums/viewthread/181742/#860506
Because jquery is in javascript folder.
Or
$autoload['libraries'] = array('database', 'session', 'javascript', 'javascript/jquery');
In the autoload.php file.
That solved the problem of loading the librairy.

You can try this, it's work to me.
in config.php
$config['javascript_location'] = 'http://localhost/ci/js/jquery.min.js';
in Controller
public function __construct() {
parent::__construct();
$this->load->library('javascript');
$this->load->library('javascript/jquery');
}
public function index(){
$d['library_src'] = $this->jquery->script();
$d['logalert']=$this->jquery->_show('#logalert',1000,"$('#logalert').html('hello world');");
$this->load->view('main',$d);
}
in view (head)
<?php echo $library_src; ?>
in view content (body)
<div class="alert alert-dismissable alert-info" id="logalert">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
</div>
in javascript view
<script type="javascript">
$(document).ready(function(){
<?php echo $logalert; ?>
};
</script>
happy coding :)

Related

Returning javascript view in Laravel

In Ruby on Rails In my controller I can do something like this:
def jstest
respond_to do |format|
format.js
end
end
This would return jstest.js.erb from the relevant views directory
jstest.js.erb
alert("Hello World")
The result being I get hello world alert.
I want to do the same thing in Laravel
In my controller I have:
public function jstest( )
{
return view('jstest');
}
in my view (which I have tried with both jstest.blade.js and just jstest.js)
but I get the error, view cannot be found.
The only way I get this to work is by calling the view jstest.blade.php and including my js in a <script> tag within this php file. but this feels a bit wrong...?
Is this even possible in Laravel? If so, where am I going wrong?
Example use case:
Imagine the following example, I have a table of comments, a user can click a delete button which will send an ajax request to delete the comment.
My Route:
Route::delete('post/comments/{comment}','commentsController#delete');
In my controller:
Public Function delete($comment)
{
$comment->delete();
return commentDeleted.js
}
commentDeleted.js:
$(#comment).remove();
So from the users perspective, they click delete and the comment disappears from their screen without loading a new page.
I don't know if Laravel supports this out of the box, but this is my take on your issue.
This is how I understood your problem: you want to specify a path to .js file as an argument to a function and you want this .js file to be immediately executed when loaded via browser.
I'd do it in these 2 steps
Create a jsview() function that accepts a path, similar to view()
Create the base .blade.php file which will be used by the above
The .blade.php contents
Assumption is that this view will be named javascript.blade.php and it's in resources/views/ directory.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="{{$path}}"></script>
</head>
<body></body>
</html>
The function
function jsview($path)
{
return view('javascript', ['path' => $path]);
}
Usage
<?php
Route::get('/test', function()
{
return jsview('/assets/my.js');
});
This answer isn't really fully complete because your browser will be loading files from public/ directory so all .js files you specify this way would be read from there. I believe Laravel does have something related to resources, but I'm not expert enough on that matter.
This is posted only to outline how to achieve something that you need, but isn't available out of the box.

base_url() not loading css file

I am trying to load a view from a controller file. If I reference my class in the view everything is fine, however if I reference a method from that class my css does not load.
Here is a simple example:
Controller file:
<?php
class Example extends CI_Controller
{
public function index ()
{
$this->load->view('myview');
}
}
In the view file this works fine:
<li>EXAMPLE</li>
But, this does not:
<li>EXAMPLE</li>
I also tried to use the site_url() function but the result was the same.
Note: I have loaded the URL helper.
Have you change your .htaccess file to remove index.php in url? then
<li>EXAMPLE</li>
it will not work.
you can try to add
<base href="<?php echo cdn_url()?>" />
into the tag <head></head>
Make sure that you have configured your config to php file properly. Then See take a look and make sure that have you removed index.php from url? if yes then remove index from every url you are targeting.I Hope it will work.
In config.php
$config['base_url'] = 'http://localhost/{your_project_folder}/';

CodeIgniter button onclick(), page redirect issue

I am very new to CodeIgniter.
I have created the controller as bellow.
<?php
class Search_Student_Ctrl extends CI_Controller
{
public function index()
{
//redirect('student_home');
$this->load->view('student_home', null);
}
}
?>
My view as bellow,
<!DOCTYPE html>
<html>
<body>
<h1>Student Management System</h1>
<button onclick="location.href='<?php echo base_url();?>Search_Student_Ctrl/index'">Search Student</button>
</body>
</html>
When I click on the button I am getting bellow error.
The requested URL /sms/Student_Home_Ctrl/index was not found on this server.
Note: I have added bellow line in autoload.php
$autoload['helper'] = array('url');
Can anyone please help me how to resolve this issue?
what happens when you just go to the url in your browser?
http://yourdomain.com/sms/Student_Home_Ctrl/index
Are you still getting the requested url was not found?
Try:
http://yourdomain.com/index.php/sms/Student_Home_Ctrl/index
Did you follow the right steps to remove index.php?
There could be a few reasons for it:
it might be because you are working on a local environment and
didn't set a host in the hosts file so the base_url cannot be found by Codeigniter (see 3. or set a local host)
you didn't loaded the Helper: $this->load->helper('url');
if all of the above still don't work you should configure the base_url in your config.php: $config['base_url'] = '';
Search_Student_Ctrl/index'">Search Student
Change above lines to
<button onclick="location.href='<?php echo site_url('Search_Student_Ctrl/index');?>'">Search Student</button>
For calling controllers from view you have to use site_url() instead of base_url()
No need to add index function url. by default controller get index function
Search_Student_Ctrl'">Search Student
Please also check your .htaccess file working or not.
You have removed index.php in url? If yes then check rewrite rule is working on your server.
In codeIgniter 3 Class is always start with capital letter for controller ass well ass models.

cakephp-2.0 simplest ajax link with jshelper

I want to create the most basic ajax link there is in Cakephp 2.0.
In index.ctp i have
<?php
echo $this->Js->link('myLink', array('controller'=>'technologies', 'action'=>'view'), array('update'=>'#success'));
?>
<div id="success"></div>
in TechnologiesController.php i have
public function view(){
$this->set('msg', 'message');
$this->render('view', 'ajax');
}
and in view.ctp i have
<?php echo $msg;?>
Instead of setting the view in the success div, it navigates to the http://local.cake.com/technologies/view page to display the message.
Any help much appreciated!
By default scripts are cached, and you must explicitly print out the cache. To do this at the end of each page, include this line just before the ending tag:
echo $this->Js->writeBuffer(); // Write cached scripts
I am using this at the end of my default.ctp in the Layouts Folder
Be sure to set $components = array('RequestHandler') in your controller
So, in total the code would look like this - and it works for me (CakePHP 2.2.4):
index.ctp:
<?php
echo $this->Js->link('myLink', array('controller'=>'technologies', 'action'=>'view'), array('update'=>'#success'));
?>
<div id="success"></div>
echo $this->Js->writeBuffer();
Thank you a lot, this helped me understand how things work in 2.0 and above :)
try $this->autoRender = FALSE;
I think you might have to put this:
echo $this->Js->writeBuffer();
somewhere - for example right below the $this->Js->link call.
Hope that helps!
I just put this:
echo $this->Js->writeBuffer();
it work for me, hope i will for you

form not picking up javascript file

I am new to Cake PHP and I had a website with regular PHP and HTML, but now I am switinching to use Cake PHP. The issue I am having is that it is not picking up the javascript for a slider I have on a menu. (But it works on the original web).
So I did the following steps, maybe you can see where I am making my mistake.
First I put the Javascript file under webroot/js
FILE javascript.js
/**
*
*/
$(document).ready(function() {
//ACCORDION BUTTON ACTION
$('div.accordionButton').click(function() {
$('div.accordionContent').slideUp('normal');
$(this).next().slideDown('normal');
});
//HIDE THE DIVS ON PAGE LOAD
$("div.accordionContent").hide();
});
Then I went to AppController and added the following line under cake/libs/controller/app_Controller
class AppController extends Controller {
var $helpers = array('Html', 'Form', 'Javascript');
}
Then, that change allowd me to add it to layout
FILE mylayout.ctp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<?php
$javascript->link('javascript.js');
</head>
<?php include 'menu_nav.php';?> //this has starting <body> tag
<?php include 'leftmenu_nav.php';?>
<div id="content" class="divContent">
<div id="mainContent" class="divMainContent" style="text-align: left;">
<?php echo $content_for_layout; ?>
</div>
</div>
<?php include 'footer.php';?> //this had end </body> tag
</html>
Now somewhere in the
$content_for_layout
there some <divs> that make use of the JS, but for some reason 1) I do not see the JS markup when i do page source and 2) It is not sliding like it used to..
Can anyone please tell me what I may be missing in this CakePHP config?.
Thank you
echo $this->Html->script('javascript.js');
echo $this->Html->script('jquery-ui-1.8.16.custom.min.js');
echo $this->Html->script('jquery.js');
echo $this->Html->script('jquery.MetaData.js');
echo $this->Html->script('jquery.min.js');
echo $this->Html->script('jquery.rating.js');
echo $this->Html->script('jquery.rating.pack.js');
echo $this->Html->script('jquery.validate.js');
echo $this->Html->script('paging.js');
echo $this->Html->script('ui.datetimepicker.js');
echo $this->Html->script('format.js');
There are a couple of things you need to check.
First, don't change anything in the cake folder. That is a big no no. If you want to have an app controller, simply create a new file name app_controller.php and put it in your /app folder. Add the following code in it.
class AppController extends Controller {
var $helpers = array('Html', 'Form', 'Javascript'); //what version are you using?
}
How you include the JS file depends on what version of cake your are using. The newer version uses the following syntax
<?php echo $this->Html->script('script'); ?>
http://book.cakephp.org/view/1589/script (1.3)
Next, make sure that all the JS is actually being included. Look at the source and click through to the JS file to confirm that the file is loaded. I don't see a jquery include anywhere so you should confirm that jquery is included in your layout.
After that, confirm that the div.accordionButton div is contained in your view. Since it doesn't look like it's in the layout, open up the specific view element and check in there.
As a last resort, add alert($('div.accordionButton').length) in your JS file to confirm that the JS is actually picking up the DIV from the view. If the alert shows 0, then this means that it's not.
You'll want to use this format instead, I insert it in my layout.ctp.
echo $this->Html->script('jquery.min.flip.js');
I think there are different ways of calling js files, but I keep them in /app/webroot/js and use this call to load the file.

Categories