Tutorial: How to find width and height of a uploaded image with JavaScript

This is more like a clever trick to find out the height and width of a uploaded image that i would like to share with you. This method most likely will be useful to you when you are dealing with asynchronous uploading which you required the width and height of the image so that you could display the size of the preview box or window. Another usage will be user will have the ability to pre-set the width and height of each images outside the upload function which will resize the uploaded image and you will either required to query the database or look up using server scripting ( both provide redundency). This method will eliminate the need of redundency of query the database or passing the data from server scripting to JavaScript. Instead, we will just required a few sentence of JavaScript to determine the width and height of the uploaded image.

Concept

Let's take an example to demonstrate the concept. Imagine you are trying to perform a asynchronous uploading function that allow users to view their uploaded images on the screen dynamically. So we can use the simple asynchronous uploading function to perform the upload function and use asynchronous complete detection function to inform the user that it has been completed. So once we know that the upload has completed, we want to preview this image to the user right? Assuming that the upload function resize this image randomly. So what is the resize width and height of this image? There are few method that can work this out,

  1. Since we are doing asynchronous upload, we can provide the width and height of the image from the server to the client script
  2. store the width and height of the new image to the database and query it using ajax function
  3. Any other method that required additional work!

This is not efficient at all. What we really need is just JavaScript alone.

  1. Upload the image
  2. Upload completed
  3. display it on the screen
  4. set the width and height to be empty ( reset the width and height to null)
  5. create a new image object and store the new image into it
  6. retrieve the new image object width and height
  7. change the width and height of the display screen to the new image object width and height
  8. Ta-Da~

Simple and clean!

JavaScript

var imgObj = document.getElementById('uploadedImage');
var newImg = new Image();
newImg.src = imgObj.attr('src');

var height = newImg.height;
var width = newImg.width;

imgObj.style.width = width;
imgObj.style.height = height;

I shall skip the codes for PHP and HTML part on how it upload the file to the server and how the server return the images (just have to echo '' after it has been uploaded to the server) to the client as it has been demonstrated on the above link provided. What the JavaScript is trying to do is to retrieve the DOM object of the preview image send in back the server side after uploaded.  It creates a image object and insert that particular preview image into this object. Thus, we have all the information we need stored into this object and placed them into the preview box.

Demo

There are no demo for this method (since i can't store the uploaded images all on the server, it will blow after sometimes) but you can use the demo previously created on asynchronous complete detection function and add a few function into it to make it randomly resize the image you placed into, provide the width and height of each uploaded images via a pop up and resize the iframe according to the new width and height.

Tutorial: How to determine an asynchronous upload completion with JavaScript and PHP

Originally, i wanted to create a progress bar with JavaScript using Ajax as assistance to prompt the server for raw post data. But it seems like PHP doesn't provides raw post data manipulation for its users. Many uses Perl, Flash, Python and etc. which you can see where i am going (Other languages instead of PHP). PHP 5.2 onwards there is an extension to help PHP user manipulate this data but it required the end users or plugin users to adjust their PHP settings to enable certain extension and variables in the PHP setting which is not what i wanted. Therefore, this tutorial is created instead which doesn't required the end users to adjust anything and will be more welcome by programmers. (messing up the setting of PHP can result to security flaws and etc.) But the fall back of this method is that they won't be able to know the progress of upload. (in term of percentage %)

Aim

The aim of this tutorial is to demonstrate a simple method to help programmers who is dealing with iFrame or Ajax (which ever you prefer to call it) upload function to keep track of the upload completion of the file. Simple and Easy is the key objective for this tutorial.

Requirement

There are a few requirement you will need other than reading this post.

  1. Asynchronous upload function - Easy asynchronous upload function using iFrame
  2. JavaScript file - this is the main function to check whether iFrame has complete uploaded the file
  3. Read!

Concept

I like to  have a concept sub section to make my reader understand how it work before showing out all the boring codes. In order to be informed that the upload process has completed, the iFrame will have to show certain message (error and complete message) so that our JavaScript can be informed with the process of the upload function. We will accomplish this with the following steps

  1. Start uploading From iFrame
  2. loading.gif start running
  3. a 'check_complete()' function is being initialize to check the iFrame for message
  4. iFrame shows a message, determine this message (error or success) and output the result accordingly

Asynchronous upload function

Unlike the previous tutorial on asynchronous upload function, i have updated some codes into the previous codes in order demonstrate this tutorial. (Please visit the simplify version of the Asynchronous upload function on the link if you find this complicated)

HTML


<form id="my_form" name="form" action="upload.php" method="POST" enctype="multipart/form-data" >

<div id="main">
<p>
MAX SIZE: 100kb<br/>
ALLOWED FILES EXTENSION: .png, .gif, .jpg, .jpeg<br/>
Other than the above mention rules, all other type of file upload will result in error alert.<br/></p>
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input name="my_files" id="my_file" size="27" type="file" />
<input type="button" name="action" value="Upload" onclick="redirect()"/>
<iframe id='my_iframe' name='my_iframe' src="">
</iframe>
</div>
<div id="loading"></div>
</form>

The only differences in this part is the instruction added for the demo to work and a div block box for the loading.gif to appear.

JavaScript


function redirect()
{
document.getElementById('my_form').target = 'my_iframe'; //'my_iframe' is the name of the iframe
document.getElementById('my_form').submit();

var iFrame = document.getElementById("my_iframe");
var loading = document.getElementById("loading");
iFrame.style.display = "none";
iFrame.contentDocument.getElementsByTagName("body")[0].innerHTML = "";
loading.style.display = "block";
checkComplete();
}

In the redirect method which is also the key to use to perform this asynchronous upload function has a few more sentences as shown above which is different from the previous method that only required the first 2 sentence. The above new codes indicate that every time the upload button is pressed, the iFrame should be reminded to be disappeared and the internal of the iFrame should be empty(no message), this sentence is there so that we can perform multiple upload without any problem. Others will required loading.gif to appear to inform the users that it is in progress and the checkComplete() method (the method is located below) is invoked to start monitor the upload completion.

PHP


<?php

$uploaddir = '/images/';
$uploadfile = $uploaddir . basename($_FILES['my_files']['name']);
$file = $_FILES['my_files'];
$allowedExtensions = array("jpg", "png", "gif", "jpeg");
if($file['error'] == UPLOAD_ERR_OK) {
if(isAllowedExtension($file['name'])) {
# Do uploading here

$uploaddir = '/images/';
$uploadfile = getcwd ().$uploaddir . basename($_FILES['my_files']['name']);

//if (move_uploaded_file($_FILES['my_files']['tmp_name'], $uploadfile)) {
echo "success";
//} else {
//  echo "error";
//}
} else {
echo "Invalid file type";
}
} else die("Cannot upload");

function isAllowedExtension($fileName) {
global $allowedExtensions;

return in_array(end(explode(".", $fileName)), $allowedExtensions);
}
?>

What i have added here which is different from the previous version is that i have added a simple validation to validate extension of the files before uploading them into the server in order to demonstrate the different message of this tutorial (error and success).

CSS

Please refer to the demo files if you are interested in the CSS of this demo.

JavaScript

Here is the main method to check for the upload completion from the iFrame.


var checkComplete = function()
{
var iFrame = document.getElementById("my_iframe").contentDocument.getElementsByTagName("body")[0];
var loading = document.getElementById("loading");

if(iFrame.innerHTML == "")
{
setTimeout ( checkComplete, 2000 );
}
else
{
if(iFrame.innerHTML == "success")
{
loading.style.display = "none";
document.getElementById("my_iframe").style.display = "block";
//successful do something here!
}
else
{
loading.style.display = "none";
alert("Error: "+ iFrame.innerHTML);
}
}
}

The first few sentences take  their DOM object for loading.gif and iframe into a variable. Then we check whether the iframe 'body' block contains any message. If there isn't any message we do a recursive loop by calling itself again after 2 second else we hide the loading.gif and show the iframe message if and only if the message in the iframe is 'success' all other message will result in alert to the screen.

Demo

Determine an asynchronous upload completion demo consist of the aim of this post. However, no files will be stored in the server as i am merely providing a demo site to demonstrate this concept. The condition for a success message to appear are stated in the demo site. If you are interested to look up the overall code in this demo, you can download the file at JavaScript-upload-completion-alert. (Please be reminded you will need to setup a webserver in order to test it in your own pc)

function redirect()
{
document.getElementById('my_form').target = 'my_iframe'; //'my_iframe' is the name of the iframe
document.getElementById('my_form').submit();

var iFrame = document.getElementById("my_iframe");
var loading = document.getElementById("loading");
iFrame.style.display = "none";
iFrame.contentDocument.getElementsByTagName("body")[0].innerHTML = "";
loading.style.display = "block";
checkComplete();
}

WordPress Database Design

Recently i have been working on WordPress plugin and related stuff a lot. There are times when i come across problems with the database of WordPress that required me to check or modify data in the table. However, i couldn't seems to find the correct source for the official WordPress database design which can really help understand a lot of the overall architecture practice of this open source application. But today i manage to find it and would like to share with people out there who can't find it because of various reason (Google fail you).

wordpress-database-design

You can find the most updated version on the WordPress official database design page (the reason why it cannot be found on search engine is because the title of the page is some weird name of the picture)

Tutorial: Easiest way to create a Asynchronous upload file function (ajax upload)

I am going to demo the simplest and easiest way of creating a asynchronous upload file function with JavaScript and PHP.  It is really easy but i take a VERY long time figuring out the method since all the goggling tutorial makes this look complicated and long. The objective is to keep thing simple, VERY SIMPLE.

Concept

Let's face the fact that Ajax cannot do a file upload asynchronously. But let's not go into argument that it can or cannot be done. The method used in this tutorial will be iframe method which is really very easy (slap myself) but i take like few hours to understand what are these people writing with so many unrelated codes. Basically we use a iframe to upload the file instead of the main window to upload it. The sideback of this method is that we cannot monitor the progress of the upload which is why Ajax come into handle in this case but i will not go into detail with the progression monitor of the upload.

Requirement

  1. HTML file - for display purposes
  2. PHP file - for the handling of the upload file
  3. JavaScript - for assisting the whole process
  4. READ

HTML

The HTML part is really very simple as shown below,


<form id="my_form" name="form" action="upload.php" method="POST" enctype="multipart/form-data" >

<div id="main">
<input name="my_files" id="my_file" size="27" type="file" />
<input type="button" name="action" value="Upload" onclick="redirect()"/>
<iframe id='my_iframe' name='my_iframe' src="">
</iframe>
</div>

</form>

I just placed the main code required, the other files can be view overall from the demo attached below. I believe everyone will know what is the above code trying to accomplished. It basically create a iframe, upload box and a button. These 3 item will be wrap around the form so that it can be uploaded by either iframe or uploadbox upon clicked of the button.

P.S: The iframe is not hidden yet, so you guys can see that it has been uploaded over there.

JavaScript

Think asynchronous upload is difficult in the JavaScript part? Think again.


function redirect()
{
document.getElementById('my_form').target = 'my_iframe'; //'my_iframe' is the name of the iframe
document.getElementById('my_form').submit();
}

This is the only function required function you need for Asynchronous upload or ajax upload whatever you call it. What it does is to change the target upload responsible to the iframe instead of the main window frame. Thus, the iframe refresh instead of the main display screen upon the click of the button. ( why do people have to complex stuff, sigh..)

PHP

I believe this part is just about handling the data, so here goes,


$uploaddir = '/images/';
$uploadfile = $uploaddir . basename($_FILES['my_files']['name']);

if (move_uploaded_file($_FILES['my_files']['my_name'], $uploadfile)) {
echo "success";
} else {
echo "error";
}

The above doesn't place constraint on the type of files that is allowed to be placed into the server. You should always add that to avoid unnecessary problem to your application. The above code will move the uploaded file to the upload folder as directed.

Demo

The files did not move the files to any location it will just print out and delete away once it has output successful to the iframe. The demo files can be downloaded from here. You must have to setup a web server to test on it.  You can view the demo here.

P.S: If you are looking for upload completion alert you can find the post at How to detemine an asynchronous upload completion with JavaScript and PHP

jQuery Menu Effect Plugin

There are 6 effects contain in this small plugin that i created casually for the purpose for making the overall menu bar more interesting. The plugin itself is quite easy to use but it may contain many unnecessary code since you will only be using a single effect of the plugin, others will be just there to sum up the size of the file. Therefore, if you would like to only use one of the effect in this small plugin, just remove the other effect located in the plugin. Feel free to see how each effect work, you can also search this site for the how-to tutorial on each of the effect in jQuery.

Information

  • Current version: 1.0
  • Licensing: MIT

Browser Tested

  • Firefox 3.0.7
  • IE 7.0.5730.13
  • Opera 9.64
  • Google Chrome
  • Safari

Dependencies

  • jQuery 1.31

Documentation

I will keep the documentation simple, each method will have certain parameter that can be adjust such as speed of the effect and etc. by default, all these effect already have their own default values. Therefore, without any changes you can also call it out by stating its method.

There are 6 effects altogether.

  1. OthersFade()
  2. OthersJump()
  3. OthersBlink()
  4. OthersRollUp()
  5. OthersRollDown()
  6. OthersVibrate()

Each effect can be viewed on the demo page.  In order to call each effect, you will just have to do the following,


$("div#menu1 ul#main li").OthersFade();
$("div#menu2 ul#main li").OthersJump();
$("div#menu3 ul#main li").OthersBlink();
$("div#menu4 ul#main li").OthersRollUp();
$("div#menu5 ul#main li").OthersRollDown();
$("div#menu6 ul#main li").OthersVibrate();

bear in mind that the selection on jquery must be pointing at the element '

  • ' and the parameter of each effect is stated below,

    OthersFade()

    • startOpacity: 1, //the start visibility
    • hoverOpacity: 0, //the hover visbility
    • duration: 2000  //the effect duration to reach hover opacity

    OthersJump()

    • jumpHeight: 15, //how height it jump
    • jumpDirection: 0, //'0' jump upwards, '1' jump downwards
    • duration: 100  //duration of the effect

    OthersBlink()

    • brightness: 0.5 //the quickness of the effect
    • duration: 100 //duration of effect

    OthersRollUp()

    • duration: 1000 //speed of effect

    OthersRollDown()

    • duration: 1000 //speed of effect

    OthersVibrate()

    • interval: 30,  // the start interval of each vibration
    • duration: 1000, // the duration of the vibration
    • shake: 3 //the area that the vibration will be moving

    Support

    • Please post bug reports and other contributions (enhancements, features, etc.) to [email protected] and i will try to get back to you asap. You can comment below to seek help too.
    • Any additional effect you would like to have in this plugin, please comment below or email me so that i can add them up.
    • There are a lot of how-to effect in this particular site, feel free to search for it and learn up yourself to get this effect on your own plugin

    Donation

    [donate]

    Update

    • initial released

    File

    Example of usage

    interval: 30,
    duration: 1000,
    shake: 3