Nasrul Hazim Bin Mohamad

jQuery: Create Loading Indicator with ajaxSend & ajaxComplete

May
27

Referring to my earlier post jQuery: Show Loading…, a better way to show & hide loading icon – by binding to ajaxSend and ajaxComplete event.

The Html Markup

 <div id="loading" class="overlay-loading">
    <i class="loading-icon fa fa-5x fa-circle-o-notch fa-spin"></i>
 </div>

The CSS

.overlay-loading {
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    background: #000;
    opacity: 0.8;
    filter: alpha(opacity=80);
    z-index: 2000;
}
.loading-icon {
    position: absolute;
    top: 50%;
    left: 50%;
}

The JavaScript

$(document).bind("ajaxSend", function(){
   $("#loading").show();
 }).bind("ajaxComplete", function(){
   $("#loading").hide();
 });

References:

  1. Ajax Events
  2. JsFiddle
  3. FontAwesome

CakePHP 2.x: Pagination Element

May
25

Being working on Bootstrap Pagination with CakePHP. Here the final one. Use it as you needed.

References:

  1. CakePHP 2.x Pagination
  2. Bootstrap Pagination
  3. CakeDC Users
<nav>
  	<ul class="pagination">	
  	<?php
		echo $this->Paginator->prev('< ' . __d('users', 'previous'), array('tag' => 'li'), null, array('disabledTag' => 'span', 'class' => 'disabled'));
		echo $this->Paginator->numbers(array(
			'separator' => '',
			'tag' => 'li',
			'currentTag' => 'span',
			'currentClass' => 'active'
		));
		echo $this->Paginator->next(__d('users', 'next') . ' >', array('tag' => 'li'), null, array('disabledTag' => 'span', 'class' => 'disabled'));
	?>
	</ul>
</nav>

jQuery: Get Non-empty Text Area Inputs

May
08

Simple solutions to get non-empty text area inputs. Let say you have a list or text area like the following:

<textarea name="remark[about_us] id="remark-about_us"></textarea>
<textarea name="remark[about_us2] id="remark-about_us2"></textarea>
<textarea name="remark[about_us3] id="remark-about_us3"></textarea>
<textarea name="remark[about_us4] id="remark-about_us4"></textarea>
<textarea name="remark[about_us5] id="remark-about_us5"></textarea>
var remarks = $('[name^=remark]');
$.each( remarks, function( index, value ){
	var remark = $.trim($('#'+value.id).val());
	if(remark.length != 0) { 
		console.log(value.id + ' - ' + value.value);
	} else {
		console.log(value.id + ' - empty');
	}
});

Here a sample I have on my current working project.

Get Non-Empty Text Area

jQuery Plugin: MySQL DateTime to Input Date Format

May
07

Simple solutions to convert MySQL DateTime to Input Date Format. You may change the format as your requirement.

$.extend({
  getInputDateFromMySQLDate: function(value) {
  	var t = value.split(/[- :]/);

	var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
	
	var day = ("0" + d.getDate()).slice(-2);
	var month = ("0" + (d.getMonth() + 1)).slice(-2);

	return d.getFullYear()+"-"+(month)+"-"+(day);
  },
  getDateFromMySQLDate: function(value){
  	var t = value.split(/[- :]/);

	return new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
  }
});

References:

  1. http://stackoverflow.com/questions/3075577/convert-mysql-datetime-stamp-into-javascripts-date-format
  2. http://stackoverflow.com/questions/12346381/set-date-in-input-type-date

Web Services: Slim Framework + Eloquent(Laravel)

May
02

Setting up the Restful API is easy with Slim Framework & Eloquent(Laravel). Here are the steps:

  1. Install required components via composer – Slim Framework + Eloquent(Laravel)
  2. Create a database called web_services and create users table.
  3. Setting up Eloquent
  4. Setting up Routes
  5. Final Touch
Web Service Restful API

Web Service Restful API

Install the necessary components using composer – create a composer.json and save it in a working directory and run composer install.

{
    "name": "Web Services",    
    "require": {
        "php": ">=5.3.0",
        "slim/slim": "2.*",
        "slim/views": "0.1.*",
        "illuminate/database": "5.0.*",
        "illuminate/events": "5.0.*"
    },
    "autoload": {
        "classmap": [
            "models"
        ]
    }
}

We’re creating a simple web services for Users – Simple CRUD. Create a database called web_services and run the following SQL statement to create user table.

CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `phone` varchar(45) DEFAULT NULL,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Next, setting up the Eloquent. Create a database.php in config folder(Please create this folder in the working directory) folder.

$database = [
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'web_services',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
];

use IlluminateDatabaseCapsuleManager as Capsule;

$capsule = new Capsule;

$capsule->addConnection($database);

// Set the event dispatcher used by Eloquent models... (optional)
use IlluminateEventsDispatcher;
use IlluminateContainerContainer;
$capsule->setEventDispatcher(new Dispatcher(new Container));

// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();

// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$capsule->bootEloquent();

Once we’re done with Eloquent, next we going to set up the routes for Users CRUD operations. Save your time, copy & paste the following codes and save it in config/routes.php.

<?php

$app->get('/api/users', function () {
    echo User::all()->toJson();
});

$app->get('/api/users/:id',  function($id) {
	try {
		echo User::find($id)->toJson();
	} catch (Exception $e) {
		echo '{"error":{"text":'. 'Unable to get the web service. ' . $e->getMessage() .'}}';
	}
});

$app->get('/api/users/search/:query', function($query) {
	echo User::where('name', '=', $query)->get()->toJson();
});

$app->post('/api/users/add', function() use ($app) {
    try {
        $user = new User;

        $user->name = $app->request()->post('name');
        $user->phone = $app->request()->post('phone');
        $user->email = $app->request()->post('email');

        if($user->save()) {
            echo '{"message":"Successfully add new user"}';
        } else {
             echo '{"message":"Failed to add new user"}';
        }
    } catch (Exception $e) {
        echo '{"error":{"text":'. 'Unable to get the web service. ' . $e->getMessage() .'}}';
    }

});

$app->put('/api/users/update/:id', function($id) use ($app) {
    try {
        $user = User::find($id);

        $user->name = $app->request()->post('name');
        $user->phone = $app->request()->post('phone');
        $user->email = $app->request()->post('email');

        if($user->save()) {
            echo '{"message":"Successfully update user info"}';
        } else {
             echo '{"message":"Failed update user info"}';
        }   
    } catch (Exception $e) {
        echo '{"error":{"text":'. 'Unable to get the web service. ' . $e->getMessage() .'}}';
    }
    
});

$app->delete('/api/users/:id', function($id) {
	$user = User::find($id);
	
    if($user->delete()) {
        echo '{"message":"Successfully delete user"}';
    } else {
         echo '{"message":"Failed to delete user"}';
    }
});

OK, here the final touch! 2 things to do, one the index.php and the other one is .htaccess. Here the index.php. Please take note, we require the header("Access-Control-Allow-Origin: *");, to ensured that we can access this Restful API from other domains. There might be security issues. Comments are welcomed.

<?php
try {
	header("Access-Control-Allow-Origin: *");
	require 'vendor/autoload.php';
	require 'config/database.php';
	require 'config/initialize.php';
} catch (Exception $e) {
	echo '{"error":{"text":'. 'Unable to start up the web service. ' . $e->getMessage() .'}}';
}

The .htaccess.

RewriteEngine On

# Some hosts may require you to use the `RewriteBase` directive.
# If you need to use the `RewriteBase` directive, it should be the
# absolute physical path to the directory that contains this htaccess file.
#
# RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

Source code available at: Web Service(Restful API)

I Have 3 demo available:

  1. Web Service App
  2. Web Service Demo
  3. Web Service Mobile Demo