Using JSONP in jQuery Ajax

PHP Server Side

    $callback = $_GET['callback'];
    $result = array();
    $result[0]['id'] = '111';
    $result[0]['title'] = 'Event1';
    $result[0]['start'] = '2014-05-10';
    $result[0]['end'] = '2014-05-12';

    $result[1]['id'] = '112';
    $result[1]['title'] = 'Event2';
    $result[1]['start'] = '2014-05-10';
    $result[1]['end'] = '2014-05-12';
    $jsdata = ($callback.'('.json_encode($result).');'); 
    echo $jsdata;

When using jsonp, it is very important to wrap the data with the callback. Try to look at the $jsdata variable, it is being wrapped by the $callback variable. That’s just how jQuery Ajax works. If you won’t wrap it with that one, you’ll get an error in your console.

Front End (Ajax and jQuery)

  jQuery.ajax({
    type:"GET",
    dataType:'jsonp',
    url: "http://mysite.com",
    error: function(xhr, status, error) {
      console.log(xhr);
      console.log(status);
      console.log(error);
    },
    success:function(data){
      console.log(data);
    }
  });

JSONP is important when trying to call an external domain in your ajax. It’s like when you’re in your http://localhost/myproject/index.php , then calling a domain at http://facebook.com/apiv1/something using ajax.

Yii Fixing failed to open stream: No such file or directory

I’ll show you how to fix Yii failed to open stream: No such file or directory when integrating an extension or a 3rd party application.

Yii::import('ext.aweber.*');
/*Disable Yii's autoloading, and do a require once*/
spl_autoload_unregister(array('YiiBase', 'autoload'));
require_once('aweber_api.php');

/*Add some of your codes...*?
/*Then just enable Yii's autoload functionality to make things back to normal again*/
spl_autoload_register(array('YiiBase', 'autoload')); // Enable Yii autoloader

Those files are just examples. I noticed this error when I started using Aweber API, then realized this might help others too when integrating an extension or a 3rd party library.

Have fun! :)

Creating SEO friendly URL using htaccess

Creating SEO friendly URL requires a knowledge on how htaccess works. Not just that, you should also be familiar with Regular Expressions but I won’t cover that one in this post though since we’ll be focusing on putting those in htaccess. Now, let’s get our hands dirty.

For example:
http://mysite.com/profile.php?username=JuanDelaCruz

If you wanted that one to become
http://mysite.com/user/JuanDelaCruz/

This is what you’re going to do:

#RewriteEngine On
#RewriteCond %{REQUEST_FILENAME} !-d 
#RewriteCond %{REQUEST_FILENAME}\.php -f 
#RewriteRule ^(.*)$ $1.php

# Use the following rule if you want to make the page like a directory
RewriteCond %{REQUEST_URI} !^/user/profile.php
RewriteRule ^user/(.*[^/])$ user/$1/ [R=301,L]

# The following rewrite the other way round:
RewriteCond %{REQUEST_URI} ^/profile.php
RewriteCond %{THE_REQUEST} ^(GET|POST|HEAD|TRACE)\ /profile.php
RewriteCond %{QUERY_STRING} id=([^&]+)
RewriteRule ^profile.php$ user/%1?

There are comments, so hope you can understand it from there.
Hope this helps someone! Have a Happy Coding! :)

How to create a zip file in PHP

Howdy!

I will show you how to create a zip file in PHP. All the directory in your server will also be zipped in the code. I will use the┬áZipArchive class in php. It’s easy as 1 2 3 :)

function ListFiles($dir) {
	if($dh = opendir($dir)) {
		$files = Array();
		$inner_files = Array();
		while($file = readdir($dh)) {
			if($file != "." && $file != ".." && $file[0] != '.') {
				if( $dir == getcwd() )	continue;
				if(is_dir($dir . "/" . $file)) {
					$inner_files = ListFiles($dir . "/" . $file);
					if(is_array($inner_files)) $files = array_merge($files, $inner_files); 
				} else {
					array_push($files, $dir . "/" . $file);
				}
			}
		}

		closedir($dh);
		return $files;
	}
}

$zip = new ZipArchive();
$backupName = date("Y-M-d-h:i:a",time());
$filename = $backupName.".zip";
#Store the backup file in a Folder called 'Files'
if( $zip->open("Files/".$filename,ZIPARCHIVE::CREATE) !== TRUE ) {
	exit("Cannot open the archive file");
}
#Replace this one with your root directory
$directory = '/home/mysite/public_html';
foreach (ListFiles($directory) as $key=>$file){
        #do not include the backup files to be backed-up 
	if( strstr($file,getcwd()) != "" ) continue; 
	$zip->addFile($file);
}  
$zip->close();

To download the zip file, just access it through your browser, so mine is I put the zip file in a File Directory, so it should be something like this: http://mysite.com/File/ . It really depends.

Hope this helps someone! Have a happy coding!

Displaying all database records in a dropdown in Yii

I will show you how to display all database records of a certain table in a dropdownlist in Yii.

Model Code:

class UserType extends CActiveRecord {
     public function GetUserType(){
	$connection=Yii::app()->db; 
	$command= $connection->createCommand("SELECT * FROM ".$this->tableName());
	$rows = $command->queryAll(); 
	return CHtml::listData($rows,'id', 'type');
     }
}

View Code:

echo $form->dropDownList($model,'user_type_id',UserType::model()->GetUserType());

The CHTML::listData() takes 3 parameters.
1st is the result of the row of your sql
2nd parameter is the value of your option. So it’s something like this <option value=”value here“>
3rd parameter is the value between <option>value here</option>