JSON is just Javascript. It is a wat to represent objects in Javascript. Using JSON does not involve working with Document Object Model (DOM). Below is a simple JSON format:
var jsnData = { "totals": [
{"location" : "First", "itemsSold" : 10, "bought": 40},
{location": "Second", "itemsSold" : 120, "bought" : 60},
{"location" : "Third", "itemsSold" : 20, "bought" : 40}
]};
Now the above JSON data can be accessed as follows:
//Get total items sold for first location
var firstItemsSold = jsnData.totals[0].itemsSold,
Similarly,
var secondItemsSold = jsnData.totals[1].itemsSold;
var secondItemsSold = jsnData.totals[1].bought;
Accessing the json based server response as json format
//lets consider basic example
//code for xmlhttprequest
if(xhr.status == 200) {
var jsnData = eval( '(' + xhr.responseText + ')' );
alert(jsnData.totals[0].itemsSold);
}
JSON is a better way to send objects or arrays to a server. And for working with such data, server should use some JSON library.
19 September, 2010
PHP Comet basics
Despite improving the user experience, Ajax still uses the HTTP model, i.e. client sending request for some resource to server and server responding to this request from client. This is generally called "Pull" method/architecture.
However, Comet, the stuff this article is on, uses "Push" architecture. Lets consider ana analogy: in case of chat systems, server pushes data to client as and when necessary at some intervals, as a result of which, communication between the two (client/server) is fast. If, chat systems would have been built using "Pull" method, then the communication would suffer.
Comet pushes information to the client via HTTP streaming. Simply saying, HTTP streaming is a continuous connection with the server that pushes data out to client at certain intervals.
Lets consider some sample code:
Since Comet focuses more on traditional web application servers, it is preferrable to use a system specially designed for HTTP streaming.
However, Comet, the stuff this article is on, uses "Push" architecture. Lets consider ana analogy: in case of chat systems, server pushes data to client as and when necessary at some intervals, as a result of which, communication between the two (client/server) is fast. If, chat systems would have been built using "Pull" method, then the communication would suffer.
Comet pushes information to the client via HTTP streaming. Simply saying, HTTP streaming is a continuous connection with the server that pushes data out to client at certain intervals.
Lets consider some sample code:
//get time the file was modified on
$changed = filemtime("some_file.txt");
$lastChanged = $changed;
//clear the file stats; so that file operation results are cleared
clearstatcache();
//check if it has changed; runs infinitely just for a test; remove this in
//real cases
while(true) {
//sleep for 3 secs; can be set as appropriate to create a delay
sleep(3);
//check the file modified time
$lastChanged = filemtime("some_file.txt");
//clear the file stats; so that file operation results are cleared
clearstatcache();
//check the times
if($changed != $lastChanged) {
$outData = date("d:i:s", $lastChanged);
?>
//send the data across HTTP stream
ob_flush();
flush();
$changed = $lastChanged;
sleep(3);
}
}
?>
Since Comet focuses more on traditional web application servers, it is preferrable to use a system specially designed for HTTP streaming.
Get age from birthdate using php the easiest way
Once i had a situation to get age of a user from his/her birthdate. After some testing, i managed to work it out. Following
code is used to get age from date. I hope this might help someone like me.
code is used to get age from date. I hope this might help someone like me.
//date in mm/dd/yyyy format; or it can be in other formats as well
$birthDate = "08/14/1972";
//explode the date to get month, day and year
$birthDate = explode("/", $birthDate);
//get age from date or birthdate
$age = (date("md", date("U", mktime(0, 0, 0, $birthDate[1], $birthDate[0], $birthDate[2]))) > date("md") ? ((date("Y")-$birthDate[2])):(date("Y")-$birthDate[2] - 1));
echo "Age is:".$age;
?>
Get current page from Codeigniter pagination
Once i had a simple problem to get current page number from codeigniter pagination. After some checks, i managed to get it working by simple one line of code. I hope this will help someone like me.
//here: $this->uri->segment(n) is the segment value that you pass when initializing pagination
//and $config['per_page'] is number of pages to be displayed during pagination initialization in codeigniter
$currentPage = floor(($this->uri->segment(n)/$config['per_page']) + 1);
echo "Current Page:".$currentPage;
16 September, 2010
Search Flickr by username using REST
Searching flickr users by username can be done simply using REST services provided by flickr. Following is a beginning but complete
code that search for a username in flick using REST service of flickr.
code that search for a username in flick using REST service of flickr.
//REST url for flickr
$url = "http://api.flickr.com/services/rest";
$data = array(
"username" => "sudhi",
"method" => "flickr.people.findByUsername",
"api_key" => "ur_api_key_here"
);
//this is the query string initialization
$q = http_build_query($data);
$finalUrl = $url."?".$q;
//initialize curl
$ch = curl_init($finalUrl);
//return the response as string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute the curl
$result = curl_exec($ch);
//use simpleXml for parsing the xml response
$xmlStr = simplexml_load_string($result);
foreach($xmlStr->user as $people) {
$attrs = $user->attributes();
//ths $attrs contains user information
echo "";";
print_r($attrs);
echo "
}
Create breadcrumb from array
Creating breadcrumbs can sometimes be really dificult. Breadcrumbs can be created from array in php using some simple code.
Following code can be used to create breadcrumbs from array, just a beginning though, and can be re-written further to make it
more flexible. Hope it helps someone like me.
Instead of using array, data can be loaded from xml file as well in order to create breadcrumbs, using the same function above.
Following code can be used to create breadcrumbs from array, just a beginning though, and can be re-written further to make it
more flexible. Hope it helps someone like me.
$id = $_GET['id'];
if ( strlen( $id ) < 1 ) $id = "home";
//this array contains page lists, with id, title and parent page named as main in here
$pages = array(
'home' => array( 'id'=>"home", 'main'=>"my_home", 'title'=>"Home",
'url'=>"bcrumb.php?id=home" ),
'members' => array( 'id'=>"users", 'main'=>"home", 'title'=>"Members",
'url'=>"bcrumb.php?id=members" ),
'sudhir' => array( 'id'=>"jack", 'main'=>"users", 'title'=>"Sudhir",
'url'=>"bcrumb.php?id=sudhir" )
);
//function to create breadcrumb from array
function crumbs( $id, $pages ) {
$bCrumbList = array();
$pageid = $id;
while(strlen($pageid) > 0) {
$bCrumbList[] = $pageid;
$pageid = $pages[ $pageid ]['main'];
}
for($i = count( $bCrumbList ) - 1; $i >= 0; $i-- ) {
$page = $pages[$bCrumbList[$i]];
if ($i > 0) {
echo( " echo( $page['url'] );
echo( "\">" );
}
echo( $page['title'] );
if ( $i > 0 ) {
echo( " | " );
}
}
}
echo "Crumbs:" .crumbs($id, $pages);
echo "
";
echo "Page:".$id;
Instead of using array, data can be loaded from xml file as well in order to create breadcrumbs, using the same function above.
08 September, 2010
Get only the path for a file
Sometimes it is required the get only the path that a file exists. In such cases following function could be of some help. I
hope this function helps someone like me
hope this function helps someone like me
function getPath($path) {
if(substr($path, -1, 1) == '/') {
return $path;
}
else {
$pathArr = explode('/', $path);
$total = count($pathArr);
$end = $pathArr[$total - 1];
if(substr_count($end, '.') > 0) {
array_pop($pathArr);
}
$finalPath = implode('/', $pathArr);
return $finalPath;
}
}
?>
Load all class at once in php
Loading all the classes at once in php can be done by a simple code. If we have requirement to load lots of php classes
at once then this can be really boring. So in order to load all class at once in php we could write some code. Following
php code does the job.
at once then this can be really boring. So in order to load all class at once in php we could write some code. Following
php code does the job.
function loadModules($dir) {
//create an array to hold the class names
$classes = array();
//usign DirectoryIterator class of php to get the handle of directory that contains the classes
$dh = new DirectoryIterator($dir);
//loop through each file
foreach($dh as $file) {
//check if the file is not a directory and ends with a .php extension
if($file->isDir() == 0 && preg_match("/[.]php$/", $file)) {
//include the class
include_once($dir."/".$file);
$class = preg_replace("/[.]php$/","", $file);
$classes []= $class;
}
}
return $classes;
}
?>
05 September, 2010
Integrating Videowhisper in CodeIgniter
Some times ago, i confronted a problem of integrating videowhisper with CodeIgniter. Searched through videowhisper forums but could not get exact solution, though i managed to do it using info regarding integration for plain php code.
I hope this might help someone like me.
Lets say we have a project folder named "test"
Step 1:
Add the "videowhisper_conference.swf" file in you root folder (project folder test) and its necessary folders like "uploads", "emoticons", etc. in the same folder
Step 2:
Copy the contents of "videowhisper_conference.php" into your view file, where you want to display the video.
Step 3:
Create function in your controller for each of the file, such as videologin for vc_login.php, videostatus for vc_status.php file. Do this for all the .php files that you require.
Step 4:
Add following code in you .htaccess file
RewriteCond %{QUERY_STRING} room_name(.*)
RewriteRule vc_login.php(.*) folder_name/controller_name/videologin/%1? [L]
RewriteRule vw_rooms.php(.*) folder_name/controller_name/videorooms/%1? [L]
RewriteRule vw_files.php(.*) folder_name/controller_name/videofiles/%1? [L]
RewriteRule vc_status.php(.*) folder_name/controller_name/videostatus/%1? [L]
and so on for all the files that you need.
You are done.
I've mentioned general steps in this case. You need to pass on the logged in user id and other required values accordingly.
Hope it helps.
I hope this might help someone like me.
Lets say we have a project folder named "test"
Step 1:
Add the "videowhisper_conference.swf" file in you root folder (project folder test) and its necessary folders like "uploads", "emoticons", etc. in the same folder
Step 2:
Copy the contents of "videowhisper_conference.php" into your view file, where you want to display the video.
Step 3:
Create function in your controller for each of the file, such as videologin for vc_login.php, videostatus for vc_status.php file. Do this for all the .php files that you require.
Step 4:
Add following code in you .htaccess file
RewriteCond %{QUERY_STRING} room_name(.*)
RewriteRule vc_login.php(.*) folder_name/controller_name/videologin/%1? [L]
RewriteRule vw_rooms.php(.*) folder_name/controller_name/videorooms/%1? [L]
RewriteRule vw_files.php(.*) folder_name/controller_name/videofiles/%1? [L]
RewriteRule vc_status.php(.*) folder_name/controller_name/videostatus/%1? [L]
and so on for all the files that you need.
You are done.
I've mentioned general steps in this case. You need to pass on the logged in user id and other required values accordingly.
Hope it helps.
25 August, 2010
Unset empty elements in Array
It is quite easier to unset empty element(s) in an array in php. Following code will do the work.
//this is a test array
$testArr = array(1 => "First", 2 => "", 3 => "Third", 4 => "", 5 =>"Fifth");
//loop through the array and remove empty elements
foreach($testArr as $key => $value) {
if(empty($value)) {
unset($testArr[$key]);
}
}
//view the array with empty elements removed
print_r($testArr);
?>
Subscribe to:
Posts (Atom)