Set and Update Charts with JQuery – Highcharts

Highcharts is a Javascript library which can be used to create interactive charts easily. The required files can be downloaded from here.

Here are some of the advantages of using Highcharts:

  • Highchart offers a wide variety of chart options.
  • Its Interactive.
  • Easy to set and update the values.
  • Provides and option to print the charts or save the charts as PDF, JPG PNG etc… (This option can be turned off as well.)
  • Highcharts come with multiple themes/color-schemes. You can use set custom colors as well.

In a recent project I got a chance to user Highcharts. The requirements were:

  • Same values has to be represented in a Bar chart and as a line chart.
  • Values should be set through JQuery.
  • The values should update based on user interactions.

So, let’s get to work.

First step is to import the Highcharts Javascript file to my code.

<script type="text/javascript" src="js/highcharts/highcharts.js">

I created two divs using bootstrap, one for bar graph and other for line graph.

Bar Chart Div

snipbar

Line Chart Div

snipline

To set the colors for Highcharts, the following code was added:

Highcharts.Color.prototype.parsers.push({
 regex: /^[a-z]+$/,
 parse: function(result){
  var rgb = new RGBColor(result[0]);
  if (rgb.ok) {
   return [rgb.r, rgb.g, rgb.b, 1]; // returns rgba to Highcharts
  }
 } 
});

To add values to the Bar chart

Highcharts.chart('AnalyticsCanvas', {
chart: {
type: 'bar',
backgroundColor: 'transparent'
},
title: {
text: ''
},
xAxis: {
categories: ["January", "February", "March", "April", "May"]
},
yAxis: {
min: 0,
title: {
text: ''
}
},
legend: {
reversed: true
},
credits: {
enabled: false
},
plotOptions: {
bar: {
stacking: 'normal',
pointWidth: 25,
borderWidth: 0
}
},
colors: ['red', 'orange', 'green', 'blue', 'purple'],
series: [{
name: "Type 1",
data: [11245, 40015, 36677, 33422, 43234]
},
{
name: "Type 2",
data: [44556, 15878, 66677, 33422, 33234]
},
{
name: "Type 3",
data: [33445, 19455, 26677, 33422, 63234]
},
{
name: "Type 4",
data: [33333, 21878, 16677, 13422, 23234]
},
{
name: "Type 5",
data: [30556, 55878, 26677, 13422, 53234]
}

]
});

Here’s the result :

Highchartbar

 

Setting the values for Line Chart

Highcharts.chart('AnalyticsLineCanvas', {

title: {
text: ''
},

subtitle: {
text: ''
},

yAxis: {
title: {
text: ''
}
},
legend: {
reversed: true
},
credits: {
enabled: false
},
xAxis: {
categories: ["January", "February", "March", "April", "May"]
},
plotOptions: {
series: {
label: {
connectorAllowed: false
}
}
},
colors: ['red', 'orange', 'green', 'blue', 'purple'], 
series: [{
name: "Type 1",
data: [11245, 40015, 36677, 33422, 43234]
},
{
name: "Type 2",
data: [44556, 15878, 66677, 33422, 33234]
},
{
name: "Type 3",
data: [33445, 19455, 26677, 33422, 63234]
},
{
name: "Type 4",
data: [33333, 21878, 16677, 13422, 23234]
},
{
name: "Type 5",
data: [30556, 55878, 26677, 13422, 53234]
}

]
});

 

Here’s the result :

Highchartline

Now to update the values.

I stored the values in a variable like shown below:

var updatedseries = [{
name: "Type 1",
data: [11245, 40015, 36677, 33422, 43234]
},
{
name: "Type 2",
data: [44556, 15878, 66677, 33422, 33234]
},
{
name: "Type 3",
data: [33445, 19455, 26677, 33422, 63234]
},
{
name: "Type 4",
data: [13234, 18885, 16677, 33422, 33234]
},
{
name: "Type 5",
data: [46774, 21675, 36677, 13422, 63234]
}
];

Then I stored the chart references in a variable like shown below:

var chart1 = $('#AnalyticsCanvas').highcharts();
var chart2 = $('#AnalyticsLineCanvas').highcharts();

Now the values must be updated based on a user interaction. Let’s assume that the user clicks on a button and our code fetches the updated values from the database. To apply the updated values to the current chart, use the following code.

chart1.update({
series: updatedseries
});
chart1.redraw();
chart2.update({
series: updatedseries
});
chart2.redraw();

This code will apply the new values to the charts and redraw the chart with the new values.
Wasn’t that simple?
Hope this helps someone. 🙂

Instamojo Payment Gateway Integration in PHP

Hello,

Instamojo is one of the easiest payment gateway to integrate in PHP. It gives your user option to pay with Cards, NetBanking and even Wallets.

After you set up an account with Instamojo, you will get an Api-Key, Auth-Token and Salt.

First Step is to pass the required data to the Instamojo API through POST method.

These are the data to be passed:

  • amount – The amount to be paid by the customer.
  • phone – Phone number of the customer.
  • buyer_name – Customer name.
  • purpose – Purpose of the payment.
  • email – Email address of the customer.

Here’s is the sample code:

Pass the Api-Key and Auth-Token here.

<?php

if((isset($_POST['amount'])) && (!empty($_POST['amount']))){
 $amount = $_POST['amount'];
 $purpose = $_POST['amount'];
 $phone = $_POST['phone'];
 $buyername = $_POST['buyername'];
 $email = $_POST['email'];

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://www.instamojo.com/api/1.1/payment-requests/');
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER,
 array("X-Api-Key:yourApiKeyHere",
 "X-Auth-Token:yourAuthTokenHere"));
$payload = Array(
 'purpose' => $purpose,
 'amount' => $amount,
 'phone' => $phone,
 'buyer_name' => $buyername,
 'redirect_url' => 'https://www.yourwebsitename.com/webhook.php',
 'webhook' => 'https://www.yourwebsitename.com/webhook.php',
 'send_email' => true,
 'send_sms' => true,
 'email' => $email,
 'allow_repeated_payments' => false
);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
$response = curl_exec($ch);
curl_close($ch); 


$data = json_decode($response,true);
var_dump($data);
$site=$data["payment_request"]["longurl"];
header('HTTP/1.1 301 Moved Permanently');
header('Location:'.$site); 

} else {
 header("Location:payment.php");
}

?>

In webhook.php, pass the Salt.

<?php
/*
Basic PHP script to handle Instamojo RAP webhook.
*/

$data = $_POST;
$mac_provided = $data['mac']; // Get the MAC from the POST data
unset($data['mac']); // Remove the MAC key from the data.
$ver = explode('.', phpversion());
$major = (int) $ver[0];
$minor = (int) $ver[1];
if($major >= 5 and $minor >= 4){
 ksort($data, SORT_STRING | SORT_FLAG_CASE);
}
else{
 uksort($data, 'strcasecmp');
}
// You can get the 'salt' from Instamojo's developers page(make sure to log in first): https://www.instamojo.com/developers
// Pass the 'salt' without <>
$mac_calculated = hash_hmac("sha1", implode("|", $data), "<yourSaltHere>");
if($mac_provided == $mac_calculated){
 $payment_id = $data['payment_id'];
 $status = $data['status'];
 $amount = $data['amount'];
 $purpose = $data['purpose'];
 if($data['status'] == "Credit"){

 // Payment was successful, mark it as successful in your database.
 // You can acess payment_request_id, purpose etc here. 
 }
 else{

 // Payment was unsuccessful, mark it as failed in your database.
 // You can acess payment_request_id, purpose etc here.
 }
}
else{
 echo "MAC mismatch";
}
?>

Here based on the data you can update status in database and redirect the user to corresponding urls.

All the instruction will be available in https://www.instamojo.com/developers/

Thanks for reading. Happy Coding.

Git basics for beginners

Git is a free and open-source software that is used for version control and for source code management.

For a beginner, it might be a little difficult to grasp the concepts of Git. So this post is for the newbies out there.

The Setup : 

First you have to download Git to your system. You can either go to https://git-scm.com/downloads/ and download, or you can use the terminal.

I am using ubuntu, so I used this command to install git:

sudo apt-get install git

Configurations:

Now let’s create a directory in out system where we will be working. Navigate to the location you want to store the project and create the directory.

mkdir myproject
cd myproject

Now initialize git in your directory :

git init

You can configure your name and email id with the following code :

git config --global user.name "yourname"
git config --global user.email "youremailid"

If you already have a repository in github or if you want to clone someone else’s code, you can do it now :

git clone /path/to/the/repository

If you are cloning from a remote server use this:

git clone username@host:/path/to/the/repository

Now you can go ahead and start coding. And you can start pushing the code.

Check the status of your code. You can see all the changes you have made here.

git status

Stage all the files to be pushed

git add .

or if you don’t want to stage every change, use

git add <filename>

Then you can go ahead and commit the changes.

git commit -m "Commit message"

Then push the code to the master branch.

git push origin master

You can pull the new changes from the remote repository to your local by pulling the code.

git pull

Branching : 

If multiple coders are working on the same repository, it’s advised to branch out from the master. You can branch out even if you want to work on something else without changing the existing code. Suppose you are going to work on a bug fix. You can create a branch for that by using :

git checkout -b branchname

Now you have made a copy of the master branch in the new branch. You can commit and push the code to this branch and it wont change the code in the master branch.

But remember to use this branch name while pushing the code

git push origin branchname

After working on the changes, you can checkout to the master branch and merge the code, if you want to.

git checkout master
git merge branchname

And delete the branch if needed

git branch -d branchname

You can check which branch you are currently in by the command

git branch

You can view the log of your commits using

git log

I think these are all the git commands that you need to know when you are starting out.

Good Luck. Happy coding.

Get Browser Details Using PHP

This PHP function can be used to get the details of the browser.


function getBrowser()
{
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$bname = 'Unknown';
$platform = 'Unknown';
$version= "";

//First get the platform?
if (preg_match('/linux/i', $u_agent)) {
$platform = 'linux';
}
elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
$platform = 'mac';
}
elseif (preg_match('/windows|win32/i', $u_agent)) {
$platform = 'windows';
}

// Next get the name of the useragent yes seperately and for good reason
if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
{
$bname = 'Internet Explorer';
$ub = "MSIE";
}
elseif(preg_match('/Firefox/i',$u_agent))
{
$bname = 'Mozilla Firefox';
$ub = "Firefox";
}
elseif(preg_match('/Chrome/i',$u_agent))
{
$bname = 'Google Chrome';
$ub = "Chrome";
}
elseif(preg_match('/Safari/i',$u_agent))
{
$bname = 'Apple Safari';
$ub = "Safari";
}
elseif(preg_match('/Opera/i',$u_agent))
{
$bname = 'Opera';
$ub = "Opera";
}
elseif(preg_match('/Netscape/i',$u_agent))
{
$bname = 'Netscape';
$ub = "Netscape";
}
else
{
$bname = 'Internet Explorer';
$ub = "MSIE";
}
//echo "B: ".$bname."<br>";

// finally get the correct version number
$known = array('Version', $ub, 'other');
$pattern = '#(?<browser>' . join('|', $known) .
')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
if (!preg_match_all($pattern, $u_agent, $matches)) {
// we have no matching number just continue
}

// see how many we have
$i = count($matches['browser']);
//echo "i: ".$i."<br>";
if($i==0)
{
$version = 11;
}
elseif ($i != 1 && $i!=0) {
//we will have two since we are not using 'other' argument yet
//see if version is before or after the name
if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
$version= $matches['version'][0];
}
else {
$version= $matches['version'][1];
}
}
else {
$version= $matches['version'][0];
}
//echo "V: ".$version;exit;

// check if we have a number
if ($version==null || $version=="") {$version="?";}

return array(
'userAgent' => $u_agent,
'name' => $bname,
'version' => $version,
'platform' => $platform,
'pattern' => $pattern
);
}

Tested In all the major browsers.

Go back to the previous page in PHP

Although there are many methods to do this, I prefer the following code to go back to the previous page in PHP.

11


session_start();
$url = basename($_SERVER['PHP_SELF']);
$query = $_SERVER['QUERY_STRING'];
if($query){
$url .= "?".$query;
}
$_SESSION['current_page'] = $url;

In the page you want to come back to, add the above code. In the variable $url, even the query string attached to the added. This helps in case you want to go back to page like userprofile.php?userid=1234567 .Store this in a session variable.

In the second page, get the value from the session variable.


session_start();
$previous_page = $_SESSION['current_page'];

To go back to the previous page using a button:


<a href="<?php echo $previous_page;?>"><button>BACK</button></a>

Or

By Using header:


header("location:$previous_page");

Hope this helps!

Re-sampling Image In PHP

When a user uploads a high quality image, you might have to reduce the image size or re-sample to show it in smaller screens or as thumbnails so the loading time can be reduced.

The below code will help you generate a copy of the original image in the destination folder and dimensions you specify.


//FUNCTION TO REDUCE IMAGE SIZE
function reduce_image_size($destination,$image_name,$files)
{
//REDUCE IMAGE RESOLUTION
if($files)
{
$dest = $destination.$image_name;
$width = 300; //in pixels
$height = 300;
list($original_width, $original_height) = getimagesize($files);
$original_ratio = $original_width/$original_height;
if ($width/$height > $original_ratio)
{
$width = $height*$original_ratio; //To maintain the aspect ratio
}
else
{
$height = $width/$original_ratio;
}
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($files);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $original_width, $original_height);
imagejpeg($image_p,$dest, 100);
ImageDestroy ($image_p);
}
//END OF REDUCING IMAGE RESOLUTION
}

Codeigniter – Placing assets folder

While many practices are followed while placing the assets folder in Codeigniter, I feel that the best place is in the root folder along with the application directory as shown below.

structure

Edit the .htaccess file as shown below :


RewriteEngine on
RewriteCond $1 !^(index\.php|assets|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

You can directly call the assets files in the View pages as shown below :


<link rel="stylesheet" type="text/css" href="assets/css/style.css">

Remove index.php from URL in Codeigniter

Open applications/config/config.php and make the following changes :

Replace


$config['index_page'] = 'index.php';

With


$config['index_page'] = '';

And add the following code to a new file and save it as .htaccess inside the root folder :


RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

Add Overlay For A Background Image In CSS

If you are looking for a cross browser solution to add an overlay to a background image with css, look no more. Here I’m adding a black transparent overlay to the header image.


background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url(img/header.jpg);
background-image: -moz-linear-gradient(top, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url(img/header.jpg);
background-image: -o-linear-gradient(top, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url(img/header.jpg);
background-image: -ms-linear-gradient(top, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url(img/header.jpg);
background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(0, 0, 0, 0.5)), to(rgba(0, 0, 0, 0.5))), url(img/header.jpg);
background-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url(img/header.jpg);

Hope this helps!

How To Capture a Page Title Using PHP

Since we know that the title of the page in html will be inside the title tag, we can use the following regular expression to capture the page title of a page easily.


$title_regex = '%&lt;title&gt;(.+)&lt;\/title&gt;%i';
$page = file_get_contents(urlencode("http://www.google.com"));
$matches = array();
 if (preg_match($title_regex, $page, $matches) && isset($matches[1]))
$title = $matches[1];
else
$title = "Not Found";
echo $title;