The title is pretty self-explanatory, but let me demonstrate. This was the dialog box that caused me a few hours of pain on Thursday and Friday:
Notice the "Hide" button? It's because I was so frustrated with the close button that I originally planned to make the contents of the dialog appear on the webpage itself, with an option for the user to hide on show the contents (with tacky buttons, imo).
Anyway, I thought at first that maybe I did not have the image file for this jQuery-UI theme. I did. Perhaps they were not being loaded properly. They were. Then I remembered that a few months ago, I was working on another website with a working dialog box, so I took a look at and the code behind it.
The button was a span element! So I took a look at the old, working jQuery-UI file and the 1.9.2 version and guess what I found out: the new one uses the button element.
(I searched for "ui-dialog-titlebar-close" in the JS file to see where the button would be created and assigned that class.)
How to fix? Good ol' copy and paste.
By replacing the button element with the span element, I finally got an image for my dialog box close button, except it wasn't quite correct.
If you've downloaded and unzipped a jQuery-UI theme, you'll know that the all the icons for jQuery-UI stuffs (like calendar arrows and dropdown triangles) are just in one file.
In the above photo, notice how you can see the edges of the icons next to the "x" in the png file. This was an exciting find for me (!!) because I always wondered why the icons weren't stored as images by themselves.
So on Friday I learned that jQuery-UI selects its icons from one PNG file through margin, width, and height attributes. (Go try it out on Firebug!) I adjusted these attributes and ended up with a properly centred "x" icon.
A better look at the fixed up CSS:
I'm not actually sure if there was an easier way to fix my close button image problem. I'm sure changing to an older version of jQuery-UI would've been the correct approach, but, to be honest, a lot of things have been breaking left, right, and center depending on what version of jQuery I've loaded, and I didn't want to take the risk with this one.
Hope this helps somebody out there. Happy coding!
Sunday, April 28, 2013
Saturday, April 6, 2013
Passing a PHP array to a Javascript Ajax call
Recently, I found myself making an Ajax call to a PHP function and needing more than just one piece of data back from it.
For those who don't know, a PHP function can "return" data to an Ajax call by echoing the data out. So, for example, given this Ajax call:
And given a function that inserts data into the database, returning/echoing data would look like:
The calling Ajax function will 'catch' $new_id with the variable msg and do whatever it wants with it.
But how about if I need more than just the new_id? Say, for example, I need the new id and a nicely formatted date of when this new id was created. I have to return these through an array, but the key is to return the array json_encoded. So I should do this:
And then in the ajax call that catches the printout, msg will catch the array, but the array has to go through $.parseJSON so that it's usable as a JavaScript array.
For those who don't know, a PHP function can "return" data to an Ajax call by echoing the data out. So, for example, given this Ajax call:
$.ajax({
type: "POST",
url: 'http://www.domainname.com/module/controller/insert',
data: { name: 'Donna Oberes', address: 'The Universe' }
}).done(function(msg) {});
And given a function that inserts data into the database, returning/echoing data would look like:
public function insert($name, $address)
{
$new_id =
$this->people_model->insert(array('name' => $name, 'address' => $address));
// Return the ID by echoing
echo $new_id;
}
The calling Ajax function will 'catch' $new_id with the variable msg and do whatever it wants with it.
But how about if I need more than just the new_id? Say, for example, I need the new id and a nicely formatted date of when this new id was created. I have to return these through an array, but the key is to return the array json_encoded. So I should do this:
public function insert($name, $address)
{
$new_id =
$this->people_model->insert(array('name' => $name, 'address' => $address));
$data = array('id' => $id, 'date' => 'April 6, 2013');
echo json_encode($data).
}
And then in the ajax call that catches the printout, msg will catch the array, but the array has to go through $.parseJSON so that it's usable as a JavaScript array.
$.ajax({
type: "POST",
url: 'http://domainname.com/module/controller/insert',
data: { name: 'Donna Oberes', address: 'The Universe' }
}).done(function(msg) {
var obj = $.parseJSON(msg);
// Print out
$('#student_list').append("New student ID " + obj.id + " added on " + obj.date);
});
Thursday, March 21, 2013
CodeIgniter-Bonfire and Images
Here is simple code for displaying images in an MVC framework like CodeIgniter-Bonfire. This entry assumes that one already has an understanding of how such a framework works.
The Database Table
Ideally, your database table would contain the following columns with the following types: id (int(11)), title (varchar(255)), mimetype (varchar(255)), filesize (int(11)), content (longblob).
The id, title, and filesize columns are self-explanatory. The mimetype is information you need later on for rendering the photo and can be obtained as you're uploading the photo. (The filesize is also something you can get when you're uploading the photo.) The content is the image itself in a binary format.
The View
At the very least, the view will have a form with one input element of type file so that you can upload the photo. Once you submit the form, you can validate the file size and the extension.
Sample form:
< form action="http://some.website.com/images/create" enctype="multipart/form-data"> < /form>
< input id="file" name="file" type="file" />
< input name="save" type="submit" value="Upload" />
The enctype must be 'multipart/form-data.' Otherwise, the $_FILES variable will not be created when you submit the form. $_FILES will contain all the file information you need. If the input box is named 'file', you can get the uploaded file's size through $_FILES['file']['size'].
Sample controller:
Displaying the image
When you want to display the image, the img tag's src should point to another function in your images controller. This function retrieves the images' content from the databases and prints it out with the appropriate headers.
Sample view
The controller function will look like the following (put this below the create() function):
And that's it! The image will be echoed out to the browser as an actual image (as opposed to the garbage it looks like in the database) because of the Content-type. Your browser knows how to interpret the following data.
The Database Table
Ideally, your database table would contain the following columns with the following types: id (int(11)), title (varchar(255)), mimetype (varchar(255)), filesize (int(11)), content (longblob).
The id, title, and filesize columns are self-explanatory. The mimetype is information you need later on for rendering the photo and can be obtained as you're uploading the photo. (The filesize is also something you can get when you're uploading the photo.) The content is the image itself in a binary format.
The View
At the very least, the view will have a form with one input element of type file so that you can upload the photo. Once you submit the form, you can validate the file size and the extension.
Sample form:
< form action="http://some.website.com/images/create" enctype="multipart/form-data"> < /form>
< input id="file" name="file" type="file" />
< input name="save" type="submit" value="Upload" />
The enctype must be 'multipart/form-data.' Otherwise, the $_FILES variable will not be created when you submit the form. $_FILES will contain all the file information you need. If the input box is named 'file', you can get the uploaded file's size through $_FILES['file']['size'].
Sample controller:
class images extends Front_Controller
{
public function create()
{
if ($_FILES['file']['size'] > 0)
{
// Get the file info
$name = $_FILES['file']['name'];
$size = $_FILES['file']['size'];
$type = $_FILES['file']['type'];
$tmpname = $_FILES['file']['tmp_name'];
// Grab the contents of the photo
$fp = fopen($tmpname, 'r');
$content = fread($fp, filesize($tmpname));
fclose($fp);
// Load your model, if your constructor doesn't
//do it for you
$this->load->model('images/Images_model',
'images_model');
$data['title'] = $name;
$data['mimetype'] = $type;
$data['filesize'] = $size;
$data['content'] = $content;
// Save the image
$insert_id = $this->images_model->insert($data);
// Now go print out a success message if $insert_id
// is an integer,or an error message if it's false
}
}
}
Displaying the image
When you want to display the image, the img tag's src should point to another function in your images controller. This function retrieves the images' content from the databases and prints it out with the appropriate headers.
Sample view
Here is a photo:
< img src="http://some.website.com/images/fetch/8" alt='a picture' />
The controller function will look like the following (put this below the create() function):
public function fetch($id)
{
$this->load->model('images/Images_model',
'images_model');
$image = $this->images_model->find($id);
ob_clean();
header("Content-type: ".$image->mimetype);
echo $photo->content;
}
And that's it! The image will be echoed out to the browser as an actual image (as opposed to the garbage it looks like in the database) because of the Content-type. Your browser knows how to interpret the following data.
Tuesday, January 29, 2013
Codeigniter Bonfire error: "Cannot redeclare function in a view file"
Well, that was annoying.
Background
I'm working with Codeigniter-Bonfire to create a web application. CI-Bonfire is an MVC framework that lets you put views within views by calling modules::run('path/to/controller/function', $arg).
Error
I kept getting this error whenever I tried to call modules::run on a function that I know works.
Fatal error: Cannot redeclare function_name() (previously declared in /path/to/view_file.php:2) in /path/to/view_file.php on line 15.
Line 2 in view_file.php is where I declare the function. Line 15 is where the function ends. I know this error comes up because I'm using view_file.php twice somehow and that's why the function is getting redeclared. But where??
Back to the controller I go and I noticed that I forgot a simple else statement.
In CI-Bonfire, you can print out a view either by itself (using the standard base_url/module/controller/function/args path) or by calling $this->load->view('view_folder/view_file', $args_array) in the controller if you've set some variable to true.
My rendering function looked like this:
if ($hmvc)
$this->load->view('view_folder/view_file', $args_array);
Template::render();
But it should've looked like this:
if ($hmvc)
$this->load->view('view_folder/view_file', $args_array);
else
Template::render();
Phew!
Background
I'm working with Codeigniter-Bonfire to create a web application. CI-Bonfire is an MVC framework that lets you put views within views by calling modules::run('path/to/controller/function', $arg).
Error
I kept getting this error whenever I tried to call modules::run on a function that I know works.
Fatal error: Cannot redeclare function_name() (previously declared in /path/to/view_file.php:2) in /path/to/view_file.php on line 15.
Line 2 in view_file.php is where I declare the function. Line 15 is where the function ends. I know this error comes up because I'm using view_file.php twice somehow and that's why the function is getting redeclared. But where??
Back to the controller I go and I noticed that I forgot a simple else statement.
In CI-Bonfire, you can print out a view either by itself (using the standard base_url/module/controller/function/args path) or by calling $this->load->view('view_folder/view_file', $args_array) in the controller if you've set some variable to true.
My rendering function looked like this:
if ($hmvc)
$this->load->view('view_folder/view_file', $args_array);
Template::render();
But it should've looked like this:
if ($hmvc)
$this->load->view('view_folder/view_file', $args_array);
else
Template::render();
Phew!
Tuesday, November 20, 2012
Using jQuery .on() rather than .onClick on dynamically generated buttons
Last week, I was beating my head over why the .click() event wasn't working with a dynamically generated button. My setup was that the buttons were given the class 'do_this' and the javascript looked like:
At first I thought maybe it was because the code wasn't inside $(document).ready(), so I put it inside one. Didn't work. Then I tried assigning the attribute and value 'onClick="runThisFunction()"' to the button instead. Still no go. (I also thought maybe I should define the Javascript functions after the buttons were generated, so I did just that. I'm not sure why it didn't work, though. It could be because the JS that rendered the buttons happened through a .post call.)
Then my co-worker pointed me to the jQuery .on() method. Surprise, surprise: it worked! The code looks like this now:
The jQuery documentation goes on to explain why .on() works and none of my previous attempts did:
So with that in mind, happy coding!
$('.do_this').click(function(){ /* insert code here */ }; At first I thought maybe it was because the code wasn't inside $(document).ready(), so I put it inside one. Didn't work. Then I tried assigning the attribute and value 'onClick="runThisFunction()"' to the button instead. Still no go. (I also thought maybe I should define the Javascript functions after the buttons were generated, so I did just that. I'm not sure why it didn't work, though. It could be because the JS that rendered the buttons happened through a .post call.)
Then my co-worker pointed me to the jQuery .on() method. Surprise, surprise: it worked! The code looks like this now:
$(document).on("click", '.add_contact', function(event) { /* insert code here */ });The jQuery documentation goes on to explain why .on() works and none of my previous attempts did:
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.See? I put everything inside
document so the class was already rendered when the Javascript bound the class to the click event.So with that in mind, happy coding!
Labels:
bonfire,
code igniter,
event handlers,
javascript,
jquery,
onclick
Saturday, October 13, 2012
Bringing up a jQuery dialogue before going to a controller
Currently, I'm using CodeIgniter/Bonfire for a website that does your basic CRUD operations. One of the functionalities the user wanted was a confirmation dialogue that the user really wanted to delete an item, which corresponds to an entry in the database. My problem was that, while I knew how to bring up jquery dialogue boxes, I wasn't sure how to redirect the dialogue to the controller that would actually delete that item from the database. My solution was to use the "id" attribute of my delete button.
While iterating through the items returned from the table, print out the name of the item and a delete button beside it. The delete button is really an anchor tag styled to look like a button.
Notice that I didn't use the href attribute. What I would've put in href, I instead put in id. If I hadn't, I wouldn't be able to call the jquery dialogue because the page would instead go to the href link.
Whenever this anchor tag is clicked, this piece of javascript would be run:
It's basic jquery, but the key is the assignment of the anchor tag's id attribute. The above code says: when an anchor tag with class 'delete' is clicked, grab that anchor tag's ID attribute and store it in variable "dest". Then look for an html element with the id "confirm_delete" and display it in a dialogue with the following height, width, and buttons: Yes and No.
Just so you know, the div with id = confirm_delete is somewhere on the page with this code:
If the user clicks on the "Yes" button, then the user will be redirected to the controller that will actually delete the item. If he chooses "No", then the dialogue just closes.
While iterating through the items returned from the table, print out the name of the item and a delete button beside it. The delete button is really an anchor tag styled to look like a button.
< a class='btn delete' id='".site_url()."modulename/controllername/function_name/{$item->id}'>Delete< /a>
Notice that I didn't use the href attribute. What I would've put in href, I instead put in id. If I hadn't, I wouldn't be able to call the jquery dialogue because the page would instead go to the href link.
Whenever this anchor tag is clicked, this piece of javascript would be run:
$('a.delete').click(function() {
var dest = $(this).attr('id');
$('#confirm_delete').css("display", "block").dialog({
height: 150,
width: 350,
modal: true,
buttons:
{
Yes: function(){
window.location = dest;
},
No: function(){
$(this).dialog('close');
}}}).dialog('open');});
It's basic jquery, but the key is the assignment of the anchor tag's id attribute. The above code says: when an anchor tag with class 'delete' is clicked, grab that anchor tag's ID attribute and store it in variable "dest". Then look for an html element with the id "confirm_delete" and display it in a dialogue with the following height, width, and buttons: Yes and No.
Just so you know, the div with id = confirm_delete is somewhere on the page with this code:
< div id="confirm_delete" style="display: none;" title="Remove item"> Are you sure you want to remove this item? </ div>
If the user clicks on the "Yes" button, then the user will be redirected to the controller that will actually delete the item. If he chooses "No", then the dialogue just closes.
Labels:
bonfire,
code igniter,
controller,
dialogue,
jquery,
php
Monday, July 9, 2012
Uploading a custom header image to the twentyeleven theme in Wordpress
This is more of a note to myself.
Right now, I am tasked with customizing the twentyeleven theme into another theme , and it involves turning off the rotating header images. After unsuccessfully doing a walkthrough of the associated code (that begins in header.php with a call to header_image()), I found the functions.php file under wp-content/themes/. In the twentyeleven_setup() function, I found a call to register_default_headers, which takes in an associative array. I only need one header image, so I deleted all but one key-value pair, renamed the key to something that made sense, and pointed the 'url' key to the photo filename. Now, although I haven't deleted any of the other header images from the directory structure, the code will only pick up the one header image I registered.
Right now, I am tasked with customizing the twentyeleven theme into another theme , and it involves turning off the rotating header images. After unsuccessfully doing a walkthrough of the associated code (that begins in header.php with a call to header_image()), I found the functions.php file under wp-content/themes/
Subscribe to:
Posts (Atom)






