Simple AJAX Unit Converter

I’ve been doing quite a bit with jQuery and AJAX as of late and have not only been impressed at the ease of implementation, but also the snappy and responsive feel that it brings to your web apps.

To demonstrate this I’m going to show you how to make a simple unit converter, which will allow you to convert units of digital storage without having to make a single page refresh.

Here’s a demo of what we’ll end up with.

First, the form

The first thing we’ll need is a form. It should have a text input field into which the user can enter the amount of units they want to convert, as well as two drop-downs, from which they can select the unit to convert from and the unit to convert into

Here’s the mark-up for that, with a minimum amount of styling applied. Note the <p> element below the form which will be used to display the result of the conversion.

Then the jQuery

Having included the latest version of the jQuery library in the head of our document, we can attach an event listener to the form, which will fire when the form is submitted:

$("#myForm").submit(function(e) {
  e.preventDefault();
  // Do some AJAX magic
});

The argument e that we pass to the anonymous function is a reference to the submit event. By writing e.preventDefault(); we can prevent our form’s default submit behaviour.

Next, let’s get a reference to some variables and implement some basic error checking:

amount = $("#amount").val();
from = $("#from").val();
into = $("#into").val();
if (amount == "" || from == "0" || into == "0"){
alert("Please fill out all of the fields!");
  return false;
}

Here we get the value of the three form elements. If the user has left the amount blank or has not selected either conversion unit, we display an alert and stop the execution of any further JavaScript.

Finally comes the AJAX:

$.ajax({
  type : "POST",
  url : "convert.php",
  data : 'amount=' + amount + '&from=' + from + '&into=' + into,
  success : function(res) {
    $("#result").html(res);
 }
});

To perform the AJAX call I’m using jQuery’s .ajax() method. There’s quite a lot going on here, so take a minute to understand everything.

First off, we are telling jQuery to submit the form data via a POST request.

We specify where the data should be sent (in this case a PHP script in the same folder entitled ‘convert.php’) and we also specify what the data should be. Note that the second, third and subsequent parameters need to be prefixed with an “&”.

Finally we are declaring a success callback. This is an anonymous function that is to be run upon the successful completion of the request. In our case we are inserting the answer from the PHP script into the <p> element below the form.

Lastly, the PHP

Let’s start off by retrieving the data which was submitted by the jQuery script, from the $_POST superglobal array

$amount = $_POST['amount'];
$from = $_POST['from'];
$into = $_POST['into'];

Now we need to work out how to convert one unit to another.

We can start by ascertaining  that one kilobyte is 1024 bytes, or two to the power of ten bytes (2^10).

Consequently, one megabyte is 2^10 kilobytes, one gigabyte is 2^20 kilobytes, one terabyte is 2^30 kilobytes and so on …

Therefore to convert one unit to another we need to know which power to raise it to, then we need to multiply it by the amount of units to be converted.

I don’t want to go too deeply into the maths at this point, but that works out as this:

$step = $from - $into;
echo pow((2),$step*10)*$amount;

And that’s all there is to it. As we are echoing the result of the calculation, it is picked up as the parameter res in our success callback and can be inserted into the correct position on the page.

Some final touches

Here’s a complete listing of the code. I’ve added a little formatting to the output of the result.

You can find a working demo here and you can download the files here:

This post currently has 6 responses

  1. Anon says:

    What if one would want arbitrary units? (Say 1 = 1000 or 0.1 but also equals 100000 but also 0.01 and so on and so forth up to one milionth)

    (1 = 100000000 should be the highest)

    What if one would want to use decimals regardless if he uses , or .

  2. oppa says:

    Thx for this tutorial. I am newbie to the php,html,javascript and so on. So, can you please help me how to make some customization, for an beautiful page?

    sorry for my english,

    • hibbard.eu says:

      Hi there,

      Thanks for your comment.

      I guess I can help you with your customizations. It depends what you have in mind.

  3. michael says:

    i want use .xml file for this demo, can u show me how i can do that, thanks u so much

Comments are closed!

I'm on Twitter:

Categories