Javascript

Overview of JSON

JSON http://www.json.org/ is an acronym for JavaScript Object Notation. It is essentially a way of exchanging data between a source and destination using name/value pairs. Commonly used when transferring data from a database to a website using AJAX.

Generating a JSON object using php is pretty simple (although it won’t be covered in this article), the lesser known technique is setting the correct content type so that the php page that generates the JSON object is seen as an actual JSON object rather than a plain text/html page.

Some libraries such as jQuery.getJSON() will detect wether or not the html page is a json response by looking at the Content-Type header of the response.

Json Content Type

What I mean by the correct content type is that each file type has its own content type which tell the browser how to handle the file. It informs the browser of what type of file follows so the browser is more aware on how to handle the content. For example a css file is seen as text/css where as an html or php file is seen as a text/html and likewise an image file can be image/jpg or image/png.

Output Json Header In PHP

As for JSON, it can be output as a javascript file but also output as a json file. To overwrite the default content of text/html that the php file will most likely be, we will set the correct headers using php’s header(); function as you can see below.

Output as Json Using PHP Headers

<?php
// set our content-type to json
// note that a Content-type of application/javascript works just as well as application/json
header('Content-Type: application/json');
// now output our json object
echo '{"name":"darian","lastname":"brown","age":87,"adress":{"21 somewhere street","my city","Australia"}}';
?>

Now when the page is loaded, the page will be seen as a JSON script rather than a simple html page.

Convert PHP Array to JSON Object

It is very easy to convert a php array into a json object using the php function json_encode(). It simply takes a multidimensional php array and converts it into a valid json string that will be read as a json object by javascript.

Overview

People access your site aren’t always in the same timezone as you are. Now perhaps you would like to determine what the time is for a user in a different country. Then here is a quick way to find this information out.

This example is very useful if you simply want to fetch your clients date and time or timezone; but also good to see what time of day (their time, not server time) your clients access your website.

Now before I should you the code, remember that PHP is server side code – ie. it runs on the server and as such doesn’t have access to the clients local time. Javascript however is client side code which means it can see the localtime but the servers time. So a combination of the two will allow us to calculate the difference.

How To Calculate Time Difference

The way the below example works, is that the client will click a submit button which sets the value of the hidden input field to their local time stamp and that gets submitted to the same php script. Then the php script checks if that value has been sent and if it has, then it gets the local time (of the server) and takes the clients times and shows a message depicting the difference.

Overview

We can use regular expressions to specify a list characters we want to either strip out of a string or replace them with other characters however this article is aimed more on how to do a regex reverse match and replace (also knows as a negative replace) where we specify the characters we DO NOT want to be stripped out which can be very useful for sanitising and cleaning out strings and prevent MySQL injections or cross-site scripting attacks. In other words we replace everything but the string specified.

Sounds simple enough yet I found it ever so difficult on how to perform this which is why I am posting it here to save others the time.

Regex Reverse Match

The below examples use the regular expression pattern /[^a-zA-Z0-9\s]/ which basically is just specifying a list of characters (being upper and lower case letters, numbers and spaces). But the big difference is the ^ (caret symbol) is inside the square brackets which tells the regular expression that it is a negative search. ie, match and strip all but the ones listed.

Remember… if we wanted to remove the list of characters specified by the expression’s pattern, then we simply exclude the ^ which mean the resulting pattern to include a list of characters would look like so: /[a-zA-Z0-9]/.

Secondly the second parameter is and empty string which will tell the function to replace the string with nothing.

Note! that if the ^ (caret) was outside the square brackets it would then specify matches at the beginning of a sentence. Just as a $ (dollar symbol) at the end of the sentence would specify matches at the end of the sentence. In this case, the ^ (caret) is inside which denotes an exclusion of characters.

PHP Reverse Replace

<?php
/* our string we will be working on */
$str = "A string - with, awful characters$@!.";
/* use php's preg_replace to execute the regular expression and echo the result */
echo preg_replace( '/[^a-zA-Z0-9\s]/', '', $str );
/* the output from the above will be "A string with awful characters" */
?>

Javascript Reverse Replace

<script type="text/javascript">
/* our string we will be working on */
var str = 'A string - with, awful characters$@!.';
/* use javascript's replace() function to execute the regular expression and then store the result */
var str = str.replace(/[^a-zA-Z0-9\s]/g,'');
/* the variable `str` from the above will be "A string with awful characters" - all nasty characters are removed */
</script>

Overview

Below is a similar post to my other post on validate email addresses example except in this post we will validate an IP address instead of an email address. I have also provided simple and straight forward code snippets for Javascript and PHP. It uses a regular expression to test if the string passed to is a check the IP address is valid.

Validate IP Address

Validate IP Address PHP And Javascript Examples

I have included both PHP and Javascript Email Validation Examples. It works perfectly for me and hope it will save you hours of time trying to find it out for yourself. Please let me know in the comments if you have any issues.

Validate IP Address In PHP With preg_match()

<?php
/* The IP to test (this IP is valid) */
$str = "100.150.200.250";
/* use php's preg_match to execute the regular expression and store the result - which is either `0` for no match or `1` for a match */
$bValidIP = preg_match( '/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/', $str );
?>

What are sprite animations?

A sprite animation is basically a large image which contains a whole bunch of smaller images. Think of it as a film strip where each frame is the next piece of animation in the sequence. The idea of sprites is that you only need to load one image and it will contain all the smaller images needed to create the animation. You simply position the background position of the sprite and it will appear to animate the sprite. For more information on sprites, check out the css button sprite tutorial.

End Result Demonstration

Above is the finished example of a flame sprite and it is what this tutorial will show you. As you can see it appears as an animation, however we simply move the background position of the larger image to create the illusion of movement.

Why should you use sprites?

Before images and css items can be displayed on your webpage, your browser must request the item such as javascript files, images, css files, etc. Each request takes time and your browser must wait for a response and then download the file for it to be displayed. So in short, the less items means less time to request and download items, meaning less time to load a page. So using sprites will increase the speed at which your website loads.

2D Sprite Animation Tutorial

Above is the large flame sprite image I am using to create the sprite animation for this tutorial. We use javascript to move the background position of the sprite image. In the below example, we do this every 100ms. To achieve smooth animation, we would need to achieve 25 frames per second, however this would increase the size of the sprite image, so we will do it a time frames per second.

Now for the code to get this all working

CSS Code

Javascript Code

Here is a quick javascript function to move the background position of the sprite animation to the next frame. We start at frame 1 and for each frame of animation we move 512px to the left since each frame is 512px wide by 512px high. Moving the background image positions every frame creates the illusion of movement, just as a movie is made up of 25 or 29 frames in a second.

<script type='text/javascript'>
$(document).ready(function(){
// call the next() function every 100 ms.
setInterval(next, 100);
});
// first frame of animation
var frame = 1;
// move the sprite animation to the next frame
// i.e. move background position to the next image in the sequence
function next()
{
// Set the position of the sprite image 512px more to the left on each frame.
var left = 512 * frame;
// top stays 0 since all the images have Y positioned at 0
var top = 0;
document.getElementById('flameanimation').style.backgroundPosition = '-'+left+'px -'+top+'px';
frame++;
}
</script>

HTML Code

Next we create the div tag where the sprite animation will be applied to.

<div id="flameanimation" title="Sprite Animation"></div>

Now as the javascript next() function runs, it will move the background image to the left which will create the illusion of animation.

Overview

You will mostly likely (or already have) reached a point where you have a PHP array and you need to be able to access that array from inside a Javascript function. You may wonder if it is possible to pass an array from PHP to Javascript. Fortunately I have created a tutorial on how this can be achieved. Below I will show you how to Pass a PHP Array to Javascript as JSON using AJAX. There are two parts to accomplish this task.

Creating The PHP Array

Firstly you need a PHP script which has the PHP array you want to pass back to Javascript. You encode the array into a JSON string using the PHP function `json_encode()`. We then echo the string into the PHP file to make it accessible to the AJAX function calling this script.

Call The PHP Script That Contains The PHP Array

Secondly we create an HTML which will contain the AJAX function to call the PHP script. We will use the jQuery `$.getJSON` function which converts the output from the PHP function ‘json_encode()’ into a JSON object. Once we have the JSON object, we can loop through it and use it as we require. We don’t really need to convert the JSON array to javascript array since we use jQuery’s ‘$.each()’ function to loop through the JSON array that is returned.

Pass a PHP Array to Javascript as JSON using AJAX

Below is the code that is to be placed into the PHP script. This file will be called by the jQuery `$.getJSON` function.

Javascript / HTML Code Snippet

Place this code into a file with the extension `.html`. The below code will call the above PHP script using AJAX and the jQuery function `$.getJSON`. The PHP script will have the PHP array encoded as a json string. Once the `$.getJSON` function returns, the Javascript function will have access to the PHP array that has been converted into a JSON object.

Passing variables to PHP using JSON and AJAX

If you would like to pass some variables to PHP you can change the parameters as shown above. In my example below, I pass the variables name and age and then the PHP function could use these to search a database or file for that person and then return that specific information as a JSON array.

Overview

When using ajax to request a page or data, there will be occasions where you will need to cancel the ajax call. I found this useful after building a search as you type feature and I would abort the previous search and request a new ajax search each time they typed a new letter. Since their old word has changed to a new meaning, completing the old request is meaningless since the new word is an entirely different category. For example the typed fee and then they type `d` making the word feed. So I would abort a previous ajax request in jquery and issue a new ajax search on feed.

Additional uses for aborting an ajax request in jquery

Another reason may be that the page you are calling enters an infinite loop and stops the call from returning. Maybe you need to cancel a previous request before making a new request to prevent duplicate requests from being sent.

How To Abort A Previous Ajax Request In jQuery

Luckily jQuery has made this almost too easy as you can see by my example below.

Now you can call the goAjax() function as often as you like and it will cancel the previous ajax request if it hasn’t been completed before making a new request preventing duplicate requests from stacking up.

Real World Unix Timestamp Examples

PHP

In PHP, you can convert a unix timestamp to a real time by using the php date() function. date() allows you to convert a timestamp that is supplied as the second parameter or if the second parameter is left out, it will convert the current timestamp to date.

<?php
/* this would display a time of 23 May 2011 17:12:pm */
echo date('d F Y H:i:a',1306134726);
/* and this would display the current time in the same format as above */
echo date('d F Y H:i:a');
?>

The way the date is displayed is controlled by the flags passed to the function. Here we used the flags ‘d’, ‘F’, ‘Y’, ‘H’, ‘i’ and ‘A’. For a complete list of flags and to see a complete description of this function, visit http://php.net/manual/en/function.date.php. The PHP function time(), strtotime() and mktime() all return the current unix timestamp. If you wanted to, you can also get a time stamp 24 hours from now by using the following code.

<?php
/* get tomorrows timestamp */
$tomorrow = time() + (24 * 60 * 60);
/* or you can use strtotime to convert a natural string into a timestamp */
$tomorrow = strtotime('+24 hours');
/* and this will create a timestamp based on the date and time variables */
$timestamp = mktime($hour,$min,$sec,$month,$day,$year);
?>

MySQL

If you have a table that contains a column with a unix timestamp in it, you can convert it using the query below. It will return a column that contains rows of easy to read date and times.

SELECT FROM_UNIXTIME(column_name) AS real_time FROM `table_name`;

Javascript

Javascript has a function called ‘Date()’ which allows you to use timestamps in javascript. Remember that since javascript is client side code (i.e. runs on the persons browser), the date shown is their own computer time, not the server time. To get the current timestamp in javascript, simple use

You can also convert a timestamp to a date by using the following javascript date functions.

<script type="text/javascript">
/* create a new date as of the current date */
var date = new Date();
/* you can also create a new date and pass a timestamp to create the date as of the timestamp */
var another_date = new Date(1306482441);
var day = date.getDate(); // get the day that date relates to
day = day < 10 ? '0' + day : day; // add a 0 if less that 10
var month = date.getMonth() + 1; // returns month as 0 - 11
var year = date.getFullYear(); // 4 digit year (eg. 2011)
var hour = date.getHours(); // get hours
hour = hour<10?'0'+hour:hour; // pad with a 0
var minute = date.getMinutes(); // and minutes
minute = minute<10?'0'+minute:minute; // pad with 0
var second = date.getSeconds(); // get seconds
second = second<10?'0'+second:second; // pad with 0
</script>

Perl

In order to retrieve the current timestamp in Perl, you can make use of the time() function which is the same as PHP.

my $timestamp = time();

Linux

Using the ‘date’ command in linux will print out the date specified by the parameters passed to it. We will use the %s flag to tell it to print the seconds passed since ‘1970-01-01 00:00:00 UTC’ (i.e. it will print out the current timestamp).

Overview – Validate Email Addresses – Javascript and PHP Example

In todays article I will show provide you with source code validate email addresses using either Javascript or PHP. It uses a regular expression to test if the string passed to is a valid email address and returns true or false in either case. It works well for me and will hopefully do the trick for you.

Use the form below to check email address is valid. Simply enter an email into the box below and hit ‘validate’ to validate the email address online. It simply makes sure the format of the email address is correct and does not verify that the email address actually exists or belongs to anyone.

Validate Email Address Online

You can get the code used to test the email address in this example by clicking here.Enter Email Address and Click Validate