How to close a Colorbox from a CodeIgniter Controller - codeigniter

I want to close Colorbox from a controller. I used this code but it will not work:
<?= "$(document).ready(function() { $.colorbox.close(); });"; ?>

To me they are two options:
a)(Easy) inside your controller print js , example:
echo "<script type='text/javascript'> parent.$.fn.colorbox.close(); </script>";
but if you after redirects with redirect("yoursite"); codeigniter will show error , the other option is:
b) you need create in view a simple .php for example close_colorbox.php , inside write this code:
if (isset($script)) { echo $script; }
After in your controller include the next code:
$data['script'] = " <script type='text/javascript'> window.top.location.reload(); parent.$.fn.colorbox.close(); </script> ";
$this->load->vars($data);
$this->load->view('close_colorbox');
*note: window.top.location.reload(); is optional if you want reload the parent content

Related

Unable to get addScriptDeclaration() to work inside a module

I have a very simple module that is loaded from a plugin via
<?php echo JHtml::_('content.prepare', '{loadposition mymodule}'); ?>
The module position is setup, and the default.php template renders the output appropriately. What doesn't work is the following:
$js = <<<FOO
(function ($) {
console.log("javascript loaded");
})(jQuery);
FOO;
$doc = JFactory::getDocument();
$doc->addScriptDeclaration($js); // no js is output in HTML here?? Why?
JModuleHelper::getLayoutPath('mod_mymodule');
The embedded javascript is not rendered with the rest of the HTML.

Constraining tank_auth views to a div on a web age

Hi Tank_auth & web Gurus!
I have tank_auth working with my CodeIgniter application. Currently, the login/register views of tank_auth take over the entire screen. On my website, I would like the login/register views to occupy a div that I define. For example, I want the login/pw fields to just appear in the top right corner and not take over the whole screen...Can you point me in the right direction? - I read somewhere that I'd have to somehow constrain the view in a div but for the life of me I did not understand how!
Much obliged,
Mmiz
Create div for the login. Create a view for the login. Populate the div with a javascript call to the view.
<?php
//controller
//users.php
class Users {
//...
public function div_login()
{
$this->load->view('div_login_view.php');
}
//...
//------------------------------------------
//view
//div_login_view.php
echo form_open('users/login');
echo form_input('username');
echo form_password('password');
echo form_submit('Login');
echo form_close();
//------------------------------------------
//index page (or whatever page you want the form on)
<div id="login_div"></div>
<script type="text/javascript">
$(document).ready(function(){
var login_form = $.get('/users/div_login');
if (login_form.status === 200){
$('#login_div').html(login_form.responseText)
}else{
alert('There was an error getting the login form.');
}
})
</script>

CodeIgniter Ajax form - submitting form

I'm new to stackoverflow and to CodeIgniter and I'm currently experimenting on some simple code examples I have found on the Internet in order to get a start. The one I'm working on right now is a form which uses CI and Ajax (jQuery) along with saving the inputs of the form in a database and then display the most recent of them on the same page as the form.
If I confused you it's the 4.7 application example from here. The initial source code lies here but I have modified it in order to work with the latest release of CI and I quote all my MVC files just below.
Controller:
<?php
class Message extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('security');
$this->load->model('Message_model');
}
function view()
{
//get data from database
$data['messages'] = $this->Message_model->get();
if ( $this->input->is_ajax_request() ) // load inline view for call from ajax
$this->load->view('messages_list', $data);
else // load the default view
$this->load->view('default', $data);
}
//when we pres the submit button from the form
function add()
{
if ($_POST && $_POST['message'] != NULL)
{
$message['message'] = $this->security->xss_clean($_POST['message']);
$this->Message_model->add($message);
}
else
{
redirect('message/view');
}
}
}
?>
Model:
<?php
class Message_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
function add($data)
{
$this->db->insert('messages', $data);
}
function get($limit=5, $offset=0)
{
$this->db->order_by('id', 'DESC');
$this->db->limit($limit, $offset);
return $this->db->get('messages')->result();
}
}
?>
Views
default.php:
<!-- called using message/view -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="<?php echo base_url('js/jquery-1.8.1.min.js'); ?>" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#submit').click(function(e)
{
e.preventDefault();
var msg = $('#message').val();
$.post("", {message: msg}, function() {
$('#content').load("");
$('#message').val('');
});
});
});
</script>
</head>
<body>
<?php echo form_open("message/add"); ?>
<input type="text" name="message" id="message">
<input type="submit" value="submit" name="submit" id="submit">
<?php echo form_close(); ?>
<div id="content"></div>
</body>
</html>
messages_list.php:
<!-- called from ajax call -->
<ol>
<?php foreach ($messages as $cur): ?>
<li><?php echo $cur->message; ?></li>
<?php endforeach; ?>
</ol>
The problem mainly lies in the 1st of the views (default.php). That is, if I omit the e.preventDefault(); line from the javascript code then the form loads a different page (message/add as the form action parameter implies) which is a blank page, also cancelling the ajax behavior of my application that way.
On the other hand, if I actually add this line then the add method of my message controller isn' t called, thus not adding what I've typed into the database.
Finally, I tried the following js code instead of the other above:
$(document).ready(function()
{
$('#submit').click(function(e)
{
e.preventDefault();
var msg = $('#message').val();
$.post("<?php echo base_url(); ?>message/add", {message: msg}, function() {
$('#content').load("");
$('#message').val('');
});
});
});
but that way it seems as the $.post() crashes because nothing is executed in the function which is supposed to run on a successful post() call.
Any help appreciated and sorry for the big post. :)
You are correct that you must call e.PreventDefault();, but you must also deal with the response from the callback function, which you are not. The callback takes a few arguments but the first one is what you're interested in, it is the response from your server. I've denoted it as r below:
$(document).ready(function(){
$('#submit').click(function(e){
e.preventDefault();
var msg = $('#message').val();
$.post("<?php echo base_url(); ?>message/add", {message: msg}, function(r) {
//do something with r... log it for example.
console.log(r);
});
});
});
I've also removed $.("#content").load(...);. This would actually perform another AJAX request when the first one is complete.
Now, inspecting your controller...please refrain from using $_POST. CodeIgniter provides you with $this->input->post() as part of the Input Library. If you turn on Global XSS filtering in config/config.php you won't have to xss clean it either. You can clean on a post-by-post basis by using $this->input->post('name', true);
I recommend this instead:
function add(){
$m = $this->input->post('message', true);
if($m){
$this->Message_model->add($m);
}
}
The problem doesn't lie with the CI, its the JS that is wrong,
$(document).ready(function()
{
$('#submit').click(function(e)
{
e.preventDefault();
var msg = $('#message').val();
$.post("<?php echo base_url(); ?>message/add", {message: msg}, function() {
$('#content').load("<?php echo base_url(); ?>/message/view");
$('#message').val('');
});
});
});
The e.preventDefault() is used to stop the default behaviour of the submit button (which will take you to message/add), which we don't want. You are correct in adding the URl paramter to the $.post() function later, but in the callback function, the .load loads the URL that is passed to it into the #content, so without passing any url, of course there won't be anything to load.

AJAX Div Refresh with PHP

I am trying to refresh some elements on my page every so often. I know theres a million topics on here about that and I have tried to get mine working, but here is what I need to refresh..
This is the code that gets generated when the page loads:
<div id="galleria">
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
$totalImgs = count($a);
$imgUsed = array();
for ($j = 0; $j < 100; $j++)
{
do
{
$randIndex = mt_rand(0, $totalImgs);
}
while ($imgUsed[$randIndex] === TRUE);
$imgUsed[$randIndex] = TRUE;
echo "<img src='" . $dir . '/' . $a[$randIndex] . "' />";
}
?>
</div>
I would like to automatically refresh this every 10 seconds but not reload the page. I have read up on ajax and it seems this is possible but I cannot seem to get it to work.
All this is doing is showing the galleria div, and loading the 100 images inside the div. Then the galleria script takes over and displays it nicely. Will AJAX work better or JQuery?
Thank you for your help!
"Will AJAX work better or jQuery?" -- AJAX is a technique, jQuery is a library. As it turns out, jQuery has an excellent API for AJAX.
Let's call this bit of PHP "galleria.php". On original page load, it is inserted into the parent PHP page using good ol' <?php include('galleria.php')?>. Now the end user is seeing the full initialized page.
To update it, you have a number of AJAX options available, but the easiest is to include jQuery on your page and then you can use .load() in a script:
var updateGallery = setInterval(function() {
$('#someDiv').load('galleria.php');
}, 10000);
There's room for tweaking... maybe galleria.php doesn't include the <div id="galleria">, which is set on the page. In which case you would load right into #galleria instead of #someDiv and save yourself an unnecessary container. Maybe you cache the $('#someDiv') object by declaring it in a different scope so that it can be re-used. But this is the general gist.
Use setInterval function with ajax call.
http://jquery-howto.blogspot.com/2009/04/ajax-update-content-every-x-seconds.html
As I wrote here you can fill a div with a jQuery ajax call.
<html>
<head>
<script type="text/javascript">
function refresh_gallery(){
$.ajax({
type: "POST",
url: "generate_gallery.php", // your PHP generating ONLY the inner DIV code
data: "showimages=100",
success: function(html){
$("#output").html(html);
}
});
}
$(function() {
refresh_gallery(); //first initialize
setTimeout(refresh_gallery(),10000); // refresh every 10 secs
});
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>

How to load more than one DIVs using AJAX-JSON combination in zend?

I am learning AJAX in zend framework step by step. I use this question as first step and accepted answer in this question is working for me. Now I want to load more than one DIVs using JSON. Here is my plan.
IndexController.php:
class IndexController extends Zend_Controller_Action {
public function indexAction() { }
public function carAction() { }
public function bikeAction() { }
}
index.phtml:
<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript" src="js/ajax.js"></script>
<a href='http://practice.dev/index/car' class='ajax'>Car Image</a>
<a href='http://practice.dev/index/bike' class='ajax'>Bike Image</a>
<div id="title">Title comes here</div>
<div id="image">Image comes here</div>
car.phtml:
<?php
$jsonArray['title'] = "Car";
$jsonArray['image'] = "<img src='images/car.jpeg'>";
echo Zend_Json::encode($jsonArray);
?>
bike.phtml:
<?php
$jsonArray['title'] = "Bike";
$jsonArray['image'] = "<img src='images/bike.jpeg'>";
echo Zend_Json::encode($jsonArray);
?>
ajax.js:
jQuery(document).ready(function(){
jQuery('.ajax').click(function(event){
event.preventDefault();
// I just need a js code here that:
// load "Car" in title div and car2.jped in image div when "Car Image" link clicked
// load "Bike" in title div and bike2.jped in image div when "Bike Image" link clicked
});
});
I think you have got this. When any link with class='ajax' is clicked then it means its AJAX call. index of array(title, image) in phtml files(car.phtml, bike.phtml) show that in which DIV this content should be loaded.
My Question:
Now how to implement ajax.js to do this job if it gets data in json form?
Thanks
Encode JSON using the Zend Framework as
echo Zend_Json::encode($jsonArray);
If you are already using JSON for serialization, then don't send the images in HTML tags. The disadvantage of doing that is basically the JavaScript code cannot do much with the images other than sticking it into the page somewhere. Instead, just send the path to the images in your JSON.
$jsonArray = array();
$jsonArray['title'] = "Hello";
$jsonArray['image'] = "<img src='images/bike.jpg' />";
On the client side, the received JSON will look like:
{
"title": "Hello",
"image": "<img src='images/bike.jpg' />"
}
So the jQuery code needs to loop through key each, and inject a new image into the div with matching key - "image1" or "image2".
jQuery('.ajax').click(function(event) {
event.preventDefault();
// load the href attribute of the link that was clicked
jQuery.getJSON(this.href, function(snippets) {
for(var id in snippets) {
// updated to deal with any type of HTML
jQuery('#' + id).html(snippets[id]);
}
});
});
YOu could encode your json to have two values for example {value1:"data",value2:"data2"}
Then when your ajax returns you can...
jQuery(document).ready(function(){
jQuery('.ajax').click(function(event){
event.preventDefault();
$.ajax({
url: '<Link to script returning json data>',
data:json, //says we are receiving json encoded data
success: function(json) {
$('#div1).html('<img src="'+json.value1+'"/>');
$('#div2).html('<img src="'+json.value2+'"/>');
}
});
});
});

Resources