Flipkart
Tuesday, December 22, 2009
Paypal sandbox form elements
// paypal_return.php,cancel_return.php,notify_return.php
// Replace business@domain.com with your test business account email id
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" name="frm" id="frm" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="upload" value="1">
<input type="hidden" name="business" value="business@domain.com">
<input type="hidden" name="item_name" value="Deposite Balance">
<input type="hidden" name="amount" value="100">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="charset" value="utf-8">
<input type="hidden" name="rm" value="2" >
<input type="hidden" name="return" id="return" value="http://yoursite/paypal_return.php" />
<input type="hidden" name="cancel_return" value="http://yoursite/cancel_return.php">
<input type="hidden" name="notify_url" value="http://yoursite/notify_return.php">
<input type="hidden" name="first_name" value="Vasim" />
<input type="hidden" name="last_name" value="Padhiyar" />
<input type="submit" value="Paypal" name="btn" />
</form>
// After Payment Complete , Paypal will return you Token in request
// on paypal_return.php
//Check This Token Transation Record on paypal server as below
$order_status = check_paypal($_REQUEST['tx']);
if($order_status=='SUCCESS')
{
// Update Database and return to main page
}
else
{
// Error msg
}
// Replace $auth_token with your appropriate token
function check_paypal($paypal_tx)
{
$status = "FAIL";
$req = 'cmd=_notify-synch';
$tx_token = $paypal_tx;
$auth_token = "03suYLK9KVmKHZMETOKW4Ad0g2uDM7R2mS0-IUd4B2tFr6E0SlDZRUVSX-G";
$req .= "&tx=$tx_token&at=$auth_token";
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('www.sandbox.paypal.com', 80, $errno, $errstr, 30);
if (!$fp)
{
$status = "FAIL";
}
else
{
fputs ($fp, $header . $req);
$res = '';
$headerdone = false;
while (!feof($fp))
{
$line = fgets ($fp, 1024);
if (strcmp($line, "\r\n") == 0)
{
$headerdone = true;
}
else if ($headerdone)
{
$res .= $line;
}
}
$lines = explode("\n", $res);
$keyarray = array();
if (strcmp ($lines[0], "SUCCESS") == 0)
{
$status = "SUCCESS";
}
else if (strcmp ($lines[0], "FAIL") == 0)
{
$status = "FAIL";
}
}
fclose ($fp);
return $status;
}
Friday, December 11, 2009
Jquery Form Validation Script
Wednesday, November 18, 2009
Play m4v Video PHP
"<video controls="controls" height="360" poster="preview.jpg" tabindex="0" width="640">
<source src="aes.m4v" type="video/mp4"></source>
<object data="aes.m4v" height="375" type="video/quicktime" width="640"> <!--<![endif]--> <param name="src" value="aes.m4v">
<param name="autoplay" value="false">
<param name="showlogo" value="false">
<!-- fallback to Flash --> <object type="application/x-shockwave-flash" data="player-viral.swf?image=preview.jpg&file=aes.m4v" width="640" height="380"> <param name="movie" value="player-viral.swf?image=preview.jpg&file=aes.m4v">
<!-- fallback message --> <img src="http://www.blogger.com/preview.jpg" width="640" height="360" /> <!-- you *must* offer a download link as they may be able to play the file locally --> </object><!--[if gt IE 6]><!--> </object>
</video>"</blockquote>
http://www.longtailvideo.com/jw/upload/mediaplayer-viral.zip
Friday, November 6, 2009
Print Div/Table css id Content
{
var DocumentContainer = document.getElementById('content');;
//alert(DocumentContainer);
var WindowObject = window.open('', "Driverlist",
"width=720,height=525,top=250,left=345,toolbars=no,scrollbars=no,status=no,resizable=no");
//alert(ctrl);
//alert(DocumentContainer.innerHTML);
WindowObject.document.write(DocumentContainer.innerHTML);
//alert(ctrl);
WindowObject.document.close();
WindowObject.focus();
WindowObject.print();
WindowObject.close();
}
Wednesday, October 21, 2009
Get Browser Details
$browsers = "mozilla msie gecko firefox ";
$browsers.= "konqueror safari netscape navigator ";
$browsers.= "opera mosaic lynx amaya omniweb";
$browsers = split(" ", $browsers);
$userAgent = strToLower( $_SERVER['HTTP_USER_AGENT']);
$l = strlen($userAgent);
for ($i=0; $i
$version = "";
$navigator = $browser;
$j=strpos($userAgent, $navigator)+$n+strlen($navigator)+1;
for (; $j<=$l; $j++){ $s = substr ($userAgent, $j, 1); if(is_numeric($version.$s) ) $version .= $s; else break; } } } if (strpos($userAgent, 'linux')) { $platform = 'linux'; } else if (strpos($userAgent, 'macintosh') || strpos($userAgent, 'mac platform x')) { $platform = 'mac'; } else if (strpos($userAgent, 'windows') || strpos($userAgent, 'win32')) { $platform = 'windows'; } if ($input==true) { return array( "browser" => $navigator,
"version" => $version,
"platform" => $platform,
"userAgent" => $userAgent);
}else{
return "$navigator $version";
}
}
checkBrowser(true)
Saturday, October 10, 2009
Get Directory Path in PHP
$_SERVER['HTTP_HOST'] ---------> Domain name
$_SERVER['DOCUMENT_ROOT'] ---------> Document Root
$_SERVER['PHP_SELF'] --------->from root Folder
$_SERVER['REMOTE_ADDR'] ------>IP Address
$_SERVER['HTTP_USER_AGENT'] ---------->User Agent
http://www.toknowmore.net/e/1/php/request-uri.php
Thursday, October 8, 2009
Email Attachment
$fileatt_type = "application/octet-stream"; // File Type
$fileatt_name = ""; // Filename that will be used for the file as the attachment
$email_from = ""; // Who the email is from
$email_subject = ""; // The Subject of the email
$email_txt = ""; // Message that the email has in it
$email_to = ""; // Who the email is too
$headers = "From: ".$email_from;
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$email_message .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$email_message . "\n\n";
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
$ok = @mail($email_to, $email_subject, $email_message, $headers);
if($ok) {
echo "The file was successfully sent!";
} else {
die("Sorry but the email could not be sent. Please go back and try again!");
}
Wednesday, September 16, 2009
Write Module in Drupal
function form_help($path, $arg) {
$output = ''; //declare your output variable
switch ($path) {
case "admin/help#form":
$output = '
'. t("Write CRUD functionalities") .'
';
break;
}
return $output;
}
/**
* Valid permissions for this module
* @return array An array of valid permissions for the onthisdate module
*/
function form_perm() {
return array('access form content');
}
/**
* Implementation of hook_block
* @param string $op one of "list", "view", "save" and "configure"
* @param integer $delta code to identify the block
* @param array $edit only for "save" operation
**/
function form_block($op = 'list', $delta = 0, $edit = array()) {
if ($op == "list") {
// Generate listing of blocks from this module, for the admin/block page
$block = array();
$block[0]["info"] = t('On CRUD FORM');
return $block;
}
else if ($op == 'view') {
// Generate our block content
// Get today's date
$today = getdate();
// calculate midnight one week ago
$start_time = mktime(0, 0, 0,
$today['mon'], ($today['mday'] - 7), $today['year']);
// we want items that occur only on the day in question, so
// calculate 1 day
$end_time = time()/*$start_time + 86400*/;
// 60 * 60 * 24 = 86400 seconds in a day
$limitnum = variable_get("form_maxdisp", 3);
$query = "SELECT nid, title, created FROM " .
"{node} WHERE created >= %d " .
"AND created <= %d"; $query_result = db_query_range($query, $start_time, $end_time, 0, $limitnum); $block_content = ''; while ($links = db_fetch_object($query_result)) { $block_content .= l($links->title, 'node/'. $links->nid) .'
';
}
// check to see if there was any content before returning
// the block view
if ($block_content == '') {
// no content from a week ago
$options = array( "attributes" => array("title" => t("More events on this day.") ) );
$link = l( t("more"), "form", $options );
$block_content .= "
$block['subject'] = 'CRUD FORM';
$block['content'] = 'Sorry No Content';
return $block;
}
// set up the block
$block = array();
$block['subject'] = 'CRUD FORM';
$block['content'] = $block_content;
return $block;
// more coming...
}
}
function form_admin() {
$form = array();
$form['form_maxdisp'] = array(
'#type' => 'textfield',
'#title' => t('Maximum number of links'),
'#default_value' => variable_get('form_maxdisp', 3),
'#size' => 2,
'#maxlength' => 2,
'#description' => t("The maximum number of links to display in the block."),
'#required' => TRUE,
);
return system_settings_form($form);
}
function form_admin_validate($form, &$form_state) {
$maxdisp = $form_state['values']['form_maxdisp'];
if (!is_numeric($maxdisp)) {
form_set_error('form_maxdisp', t('You must enter an integer for the maximum number of links.'));
}
else if ($maxdisp <= 0) { form_set_error('form_maxdisp', t('Maximum number of links must be positive.')); } } function form_menu() { $items = array(); $items['admin/settings/form'] = array( 'title' => 'On this date module settings',
'description' => 'Description of your On this date settings page',
'page callback' => 'drupal_get_form',
'page arguments' => array('form_admin'),
'access arguments' => array('access administration pages'),
'type' => MENU_NORMAL_ITEM,
);
$items['form'] = array(
'title' => 'On Form',
'page callback' => 'form_all',
'access arguments' => array('access form content'),
'type' => MENU_CALLBACK
);
$items['empform'] = array(
'title' => 'ADD Employee Details',
'page callback' => 'form_add',
'access arguments' => array('access add employees content'),
'type' => MENU_CALLBACK
);
$items['emplist'] = array(
'title' => 'ADD Employee Details',
'page callback' => 'emp_list',
'access arguments' => array('access list employees content'),
'type' => MENU_CALLBACK
);
$items['empedit'] = array(
'title' => 'Edit Employee Details',
'page callback' => 'emp_edit',
'access arguments' => array('access edit employees content'),
'type' => MENU_CALLBACK
);
return $items;
}
function form_add() {
$page_content = '';
$page_content .= drupal_get_form('form_add_form');
return $page_content;
}
function form_add_form() {
if(isset($_GET['id'])) {
//print_r($_GET['id']);
$res = db_query("select * from employees where id=".$_GET['id']);
$data = db_fetch_object($res);
$ename = $data->ename;
$add1= $data->add1;
}
$form = array();
$form['ename'] = array(
'#type' => 'textfield',
'#size' => 25,
'#id' => 'ename',
'#title' => t('Employee Name'),
'#default_value' => ($ename ? $ename : ''),
'#required' => TRUE,
);
$form['add1'] = array(
'#type' => 'textarea',
'#id' => 'add1',
'#cols' => 25,
'#rows' =>2,
'#resizable' => false,
'#default_value' => ($add1 ? $add1 : ''),
'#title' => t('Address1'),
);
$form['add2'] = array(
'#type' => 'textarea',
'#id' => 'add2',
'#cols' => 25,
'#rows' =>2,
'#resizable' => false,
'#default_value' => ($data->add2 ? $data->add2 : ''),
'#title' => t('Address2'),
);
$form['phone'] = array(
'#type' => 'textfield',
'#size' => 25,
'#id' => 'phone',
'#default_value' => ($data->phone ? $data->phone : ''),
'#title' => t('Phone Number'),
);
$form['email'] = array(
'#type' => 'textfield',
'#size' => 25,
'#id' => 'email',
'#title' => t('Email'),
'#default_value' => ($data->email ? $data->email : ''),
'#required' => TRUE,
);
$form['salary'] = array(
'#type' => 'textfield',
'#size' => 25,
'#id' => 'salery',
'#default_value' => ($data->salary ? $data->salery : ''),
'#title' => t('Salary'),
);
$form['dept'] = array(
'#type' => 'textfield',
'#size' => 25,
'#id' => 'dept',
'#default_value' => ($data->dept ? $data->dept : arg(4)),
'#title' => t('Department'),
);
if(isset($_GET['id'])) {
$form['id'] = array(
'#type' => 'hidden',
'#title' => t('Name'),
'#default_value' =>$data->id,
);
$form['update'] = array(
'#type' => 'submit',
'#value' => t('Update')
);
}else{
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit')
);
}
return $form;
}
function form_add_form_validate($form_id, $form) {
if (!valid_email_address($form['values']['email'])) {
form_set_error('email', 'Please enter valid Email');
}
}
function form_add_form_submit($from_id, $form_values) {
//print_r($form_values);
if(isset($form_values['values']['id'])) {
db_query("update employees set ename='".$form_values['values']['ename']."',add1='".$form_values['values']['add1']."',add2='".$form_values['values']['add2']."',phone='".$form_values['values']['phone']."',email='".$form_values['values']['email']."',salary='".$form_values['values']['salary']."',dept='".$form_values['values']['dept']."' where id='".$form_values['values']['id']."'");
}else{
db_query("insert into employees(ename,add1,add2,phone,email,salary,dept) values('".$form_values['values']['ename']."','".$form_values['values']['add1']."','".$form_values['values']['add2']."','".$form_values['values']['phone']."','".$form_values['values']['email']."','".$form_values['values']['salary']."','".$form_values['values']['dept']."')");
}
drupal_goto('emplist');
}
function emp_list() {
$page_content = '';
$page_content = 'Add Employees';
$page_content .= drupal_get_form('emp_list_form');
return $page_content;
}
function emp_list_form() {
$form = array();
$list = db_query('select * from employees');
while($res = db_fetch_array($list)) {
$data[] = $res;//print_r($res);
}
$cn = count($data);
for($i=0;$i<$cn;$i++) { $form['check'.$i] = array( '#type' => 'checkbox',
'#default_value'=> 0,
'#return_value' => $data[$i]['id'],
'#title'=> t($data[$i]['ename'].' Edit')
);
}
$form['count'] = array(
'#type' => 'hidden',
'#title' => t('Name'),
'#default_value' =>$cn,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Delete Selected')
);
return $form;
}
function emp_list_form_submit($form_id,$form_values) {
//print_r($form_values['values']);
for($i=0;$i<$form_values['values']['count'];$i++) { if($form_values['values']['check'.$i] != '') { $empids[] = $form_values['values']['check'.$i]; } } //print_r($empids); $cnt = count($empids); foreach($empids as $key=>$value) {
db_query('delete from employees where id="'.$value.'"');
}
drupal_goto('emplist');
}
// function emp_edit() {
//
// $page_content = '';
// $page
//
// }
function form_all() {
// content variable that will be returned for display
$page_content = '';
// Get today's date
$today = getdate();
// calculate midnight one week ago
$start_time = mktime(0, 0, 0, $today['mon'], ($today['mday'] - 7), $today['year']);
// we want items that occur only on the day in question,
// so calculate 1 day
$end_time = time();
// 60 * 60 * 24 = 86400 seconds in a day
$query = "SELECT nid, title, created FROM " .
"{node} WHERE created >= '%d' " .
" AND created <= '%d'"; // get the links (no range limit here) $queryResult = db_query($query, $start_time, $end_time); while ($links = db_fetch_object($queryResult)) { $page_content .= l($links->title, 'node/'.$links->nid) . '
';
}
if ($page_content == '') {
// no content from a week ago, let the user know
$page_content = "No events occurred on this site on this date in history.";
}
return $page_content;
// More coming....
}
function emptest_form() {
$form['#attributes'] = array('enctype' => "multipart/form-data");
$year = drupal_map_assoc(array('Select','2000','2001','2002','2003','2004'));
$form['select'] = array(
'#type' => 'select',
'#title' => t('Year'),
'#options' => $year
);
$form['radio'] = array(
'#type' => 'radios',
'#title' => 'Gender',
// '#default_value' => 1,
'#options' => array(t('Male'), t('Female')),
);
$today = getdate();
//$dt=$today['mday'].'/'.$today['mon'].'/'.$today['year'];
$form['date'] = array(
'#type' => 'date',
'#title' => t('date'),
'#default_value' => array('year' => $today['year'], 'month' => $today['mon'], 'day' => $today['mday']),
);
$form['upload'] = array(
'#type' => 'file',
'#title' => t('Attach new file'),
'#size' => 40,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit')
);
return $form;
}
function emptest_form_submit($formid,$form_values) {
//print_r($_FILES['files']['name']['upload']);
$dir = drupal_get_path('module', 'fileupload') . '/files'; //echo base_path();
if(isset($_FILES['files']['name']['upload'])){
$name = $_FILES['files']['name']['upload'];
$size = $_FILES['files']['size']['upload'];
$type = $_FILES['files']['type']['upload'];
$tmp = $_FILES['files']['tmp_name']['upload'];
$file = file_save_upload('upload', array() , $dir);
if($file){
drupal_set_message("You uploaded $name, it is $size bytes, and has a mimetype of $type.");
}
else{
drupal_set_message("file upload failure");
}
}
}
Tuesday, September 15, 2009
Sample Cake PHP Application
----------------------
data)) {
$user_check['email'] = $this->data['User']['email'];
$user_check['password'] = $this->data['User']['password'];
$users = $this->User->find($user_check);
if(isset($users['User']['id'])) {
$this->Session->write('User',$users);
$this->redirect(array('controller'=>'users','action'=>'home'));
}else{
$this->Session->setFlash('Please Check the user details provided');
}
}
}
function home() {
$this->LoginRequired();
$this->set('name',$this->Session->read('User'));
}
function logout() {
$this->Session->delete('User');
$this->Session->setFlash('You have successfully logout');
$this->redirect('/');
}
function register() {
if(!empty($this->data)) {
$user_email['email'] = $this->data['User']['email'];
$check_user = $this->User->find($user_email);//print_r($check_user);
if(empty($check_user['User']['id'])) {
if($this->User->save($this->data)) {
$this->redirect('/');
}else{
$this->set('error',false);
//$this->render();
}
}else{
$this->Session->setFlash('Email Already Exist');
}
}
}
function listusers() {
$users = $this->User->find('all');
$this->set('users',$users);
}
function userdetails($id) {
$this->User->id = $id;
$user = $this->User->read();
print_r($user);
}
function edituser($id) {
$this->User->id = $id;
if(empty($this->data)) {
$this->data = $this->User->read();
}else{
$this->User->save($this->data);
}
//$this->set('user',$user);
}
}
?>
Model
-----------------
array( 'required' => 'true', 'message' =>'Please Enter E-mail address'),
'email' => array(
'Invalid Email format' => VALID_EMAIL,
'Please Enter Email'=>VALID_NOT_EMPTY
),
'password'=>array(
'Enter Password'=>VALID_NOT_EMPTY,
'Password must be at least 4 characters in length' => array(
'rule'=>array('minLength', 4)
)
)
);
}
?>
Friday, August 7, 2009
Adding and Removing Options in Selectbox Using JS
function addoption(text,id) {
var feed = document.form.selectboxname;
var flag=true;
for (i=0;i<feed.length;i++) &&="" (!flag)="" (feed.options[i].value="=id)" (feed.selectedindex="" );="" alert(="" already="" feed.options[feed.length]="new" feed="document.form.selectboxname;" flag){="" flag="false;" function="" id);="" id="" if(text="" if="" inserted="" option(text,="" remove_category()="" var="" {="" }="" }else{="">= 0) feed.remove(feed.selectedIndex);
}</feed.length;i++)>
Wednesday, August 5, 2009
Charecter Count
function countLineBreaks(obj){
var iLength = obj.value.length;
var strLineBreaks = obj.value.match(new RegExp("(\\n)", "g"));
var countLineBreaks = strLineBreaks ? strLineBreaks.length : 0;
return countLineBreaks;
}
function textCounter(field, counter_field, maxlimit) {
var lineBreaks = countLineBreaks(field);
var adjust = isInternetExplorer ? 1 : 0;
if (field.value.length - lineBreaks * adjust > maxlimit){
field.value = field.value.substring(0, maxlimit + lineBreaks * adjust);
field.focus();
} else {
counter_field.value = maxlimit - field.value.length + lineBreaks * adjust;
}
}
textarea name="summary_desccription" id="summary_description" rows="5" onKeyDown="textCounter(this.form.summary_desccription,this.form.remLen,10);" onKeyUp="textCounter(this.form.summary_desccription,this.form.remLen,10);"
Wednesday, July 22, 2009
Get Client Computer Screen Size In PHP
//scriptlanguage="javascript"
writeCookie();
function writeCookie() {
var enddate = new Date("December 31, 2060");
document.cookie = "screenresolution="+ screen.width +"x"+ screen.height + ";expires=" + enddate.toGMTString();
window.location.replace("phptag $_SERVER['PHP_SELF'] .'?'.$_SERVER['QUERY_STRING'] phpend");
}
/script
http://www.winasm.net/forum/index.php?showtopic=1178
Seconds to HH:MM:SS
$days = floor($seconds/86400);
$days_mod = $seconds%86400;
$hours = floor($days_mod/3600);
$hours_mod = $days_mod%3600;
$minutes = floor($hours_mod/60);
$minutes_mod = $hours_mod%60;
$seconds = floor($minutes_mod);
echo $minutes.'minutes and '.$seconds.' seconds';
Monday, July 20, 2009
Differance Between Two Dates
$now2 = strtotime(date("Y-m-d h:i:s"));
$seconds = $now1-$now2;
$minutes = $now1-$now2/60;
Saturday, July 18, 2009
Image Resize
$a = getimagesize($img);
$image_attribs = getimagesize($img);
if($a['mime'] == "image/jpeg") {
$im_old = imageCreateFromJpeg($img);
}else if($a['mime'] == "image/png") {
$im_old = imageCreateFrompng($img);
}else if($a['mime'] == "image/gif") {
$im_old = imageCreateFromgif($img);
}
$th_max_width = $w;
$th_max_height = $h;
if($w >99 && $h>99){
$ratio = ($width > $height) ? $th_max_width/$image_attribs[0] : $th_max_height/$image_attribs[1];
$th_width = $image_attribs[0] * $ratio;
$th_height = $image_attribs[1] * $ratio;
}else{
$th_width=$w;
$th_height=$h;
}
$im_new = imagecreatetruecolor($th_width,$th_height);
imageAntiAlias($im_new,true);
imageCopyResampled($im_new,$im_old,0,0,0,0,$th_width,$th_height, $image_attribs[0], $image_attribs[1]);
header("Content-type:".$a['mime']);
imageJpeg($im_new,$th_file_name,100);
}
$img = base64_decode($_GET['src']);
//$img = PATH.$img;
$width = $_GET['w'];
$height = $_GET['h'];
$val = image($img,$width,$height);
Convert videos to FLV in one line..
exec("ffmpeg -i $srcFile -ar 22050 -ab 32 -f flv -s 320x240 $destFile");
where $srcFile is the location of the source file and $destFile is the location of the destination file.
Wednesday, July 15, 2009
Mysql : Get Auto increment value
WHERE table_name = 'club_photogallery'
Left Joins
SELECT
FROM
LEFT JOIN
ON Table1.column = Table2.column
Mysql: Exporting and Importing Dat
'''Exporting Data'''
SELECT
FROM
INTO OUTFILE '/tmp/vworks/sample.txt'
'''Importing data'''
LOAD DATA INFILE 'file_name.txt'
INTO TABLE tbl_name (field1, field2...etc)
Mysql : Get UnMatched Records from table1
Ajax Onclick Evaluation
if (window.XMLHttpRequest) {
http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
handle = document.getElementById('budget');
var morebutton = document.getElementById('more');
var url = 'reward.php?';
if(handle.value.length > 0) {
var fullurl = url + 'budget='+handle.value;
http.open("GET", fullurl, true);
http.send(null);
http.onreadystatechange = statechange_reward;
morebutton.disabled=false;
}else{
document.getElementById('reward').innerHTML = '';
}
}
function statechange_reward() {
if (http.readyState == 4) {
var xmlObj = http.responseXML;
var html = xmlObj.getElementsByTagName('result').item(0).firstChild.data;
document.getElementById('reward').innerHTML = html+' £';
}
}
function GetDetails() {
var amount = document.getElementById('budget').value;
if(amount == '') {
alert('Please enter value to get More Deatails');
return false;
}else{
location.href='budget_reward/'+amount;
}
}
type="button" id="rwd" value="Get Reward" onclick="toggle_budget()"
http://www.captain.at/howto-ajax-form-post-request.php
User Name validation
var charCode = (evt.which != undefined) ? evt.which : evt.keyCode;
//alert(charCode);
if((charCode >= 65 && charCode <= 90) || (charCode >=97 && charCode <= 122) || charCode == 32 || charCode == 8 || charCode == 0 || charCode == 46)
return true;
return false;
}
onkeypress="return checkname(event);
Text Area Max length validation
var charCode = (evt.which != undefined) ? evt.which : evt.keyCode;
if(ref == 'address') {
if(value.length>100){
if(charCode==8) {
return true;
}
return false;
}
}
}
onkeypress="return count1(value,event,'address')"
Text field Enter key submit Restriction Validation
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
Url, Email Validation
function validate() { var url=document.getElementById("url").value; if(url=='') { alert("url should nt be empty"); }else { var v = new RegExp(); v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"); if (!v.test(url)) { alert("wrong url"); }else{ alert("url ok");} } }Email Validation:
function validate(){ var email=document.getElementById('email').value; if(email=='') { alert('email should nt be empty'); }else { var regex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if(!regex.test(email)) { alert('wrong email'); }else{ alert('Email ok');} } }
database normalization basics
Normalization is the process of organizing data in a database. This includes creating tables and establishing relationships between those tables according to rules designed both to protect the data and to make the database more flexible by eliminating redundancy and inconsistent dependency.
Redundant data wastes disk space and creates maintenance problems. If data that exists in more than one place must be changed, the data must be changed in exactly the same way in all locations. A customer address change is much easier to implement if that data is stored only in the Customers table and nowhere else in the database.
What is an "inconsistent dependency"? While it is intuitive for a user to look in the Customers table for the address of a particular customer, it may not make sense to look there for the salary of the employee who calls on that customer. The employee's salary is related to, or dependent on, the employee and thus should be moved to the Employees table. Inconsistent dependencies can make data difficult to access because the path to find the data may be missing or broken.
There are a few rules for database normalization. Each rule is called a "normal form." If the first rule is observed, the database is said to be in "first normal form." If the first three rules are observed, the database is considered to be in "third normal form." Although other levels of normalization are possible, third normal form is considered the highest level necessary for most applications.
As with many formal rules and specifications, real world scenarios do not always allow for perfect compliance. In general, normalization requires additional tables and some customers find this cumbersome. If you decide to violate one of the first three rules of normalization, make sure that your application anticipates any problems that could occur, such as redundant data and inconsistent dependencies.
The following descriptions include examples.
First Normal Form
- Eliminate repeating groups in individual tables.
- Create a separate table for each set of related data.
- Identify each set of related data with a primary key.
Do not use multiple fields in a single table to store similar data. For example, to track an inventory item that may come from two possible sources, an inventory record may contain fields for Vendor Code 1 and Vendor Code 2.
What happens when you add a third vendor? Adding a field is not the answer; it requires program and table modifications and does not smoothly accommodate a dynamic number of vendors. Instead, place all vendor information in a separate table called Vendors, then link inventory to vendors with an item number key, or vendors to inventory with a vendor code key.
Second Normal Form
- Create separate tables for sets of values that apply to multiple records.
- Relate these tables with a foreign key.
Records should not depend on anything other than a table's primary key (a compound key, if necessary). For example, consider a customer's address in an accounting system. The address is needed by the Customers table, but also by the Orders, Shipping, Invoices, Accounts Receivable, and Collections tables. Instead of storing the customer's address as a separate entry in each of these tables, store it in one place, either in the Customers table or in a separate Addresses table.
Third Normal Form
- Eliminate fields that do not depend on the key.
Values in a record that are not part of that record's key do not belong in the table. In general, any time the contents of a group of fields may apply to more than a single record in the table, consider placing those fields in a separate table.
For example, in an Employee Recruitment table, a candidate's university name and address may be included. But you need a complete list of universities for group mailings. If university information is stored in the Candidates table, there is no way to list universities with no current candidates. Create a separate Universities table and link it to the Candidates table with a university code key.
EXCEPTION: Adhering to the third normal form, while theoretically desirable, is not always practical. If you have a Customers table and you want to eliminate all possible interfield dependencies, you must create separate tables for cities, ZIP codes, sales representatives, customer classes, and any other factor that may be duplicated in multiple records. In theory, normalization is worth pursing. However, many small tables may degrade performance or exceed open file and memory capacities.
It may be more feasible to apply third normal form only to data that changes frequently. If some dependent fields remain, design your application to require the user to verify all related fields when any one is changed.
Other Normalization Forms
Fourth normal form, also called Boyce Codd Normal Form (BCNF), and fifth normal form do exist, but are rarely considered in practical design. Disregarding these rules may result in less than perfect database design, but should not affect functionality.
Normalizing an Example Table
These steps demonstrate the process of normalizing a fictitious student table.
- Unnormalized table:
Collapse this tableExpand this tableStudent# Advisor Adv-Room Class1 Class2 Class3 1022 Jones 412 101-07 143-01 159-02 4123 Smith 216 201-01 211-02 214-01 - First Normal Form: No Repeating Groups
Tables should have only two dimensions. Since one student has several classes, these classes should be listed in a separate table. Fields Class1, Class2, and Class3 in the above records are indications of design trouble.
Spreadsheets often use the third dimension, but tables should not. Another way to look at this problem is with a one-to-many relationship, do not put the one side and the many side in the same table. Instead, create another table in first normal form by eliminating the repeating group (Class#), as shown below:
Collapse this tableExpand this tableStudent# Advisor Adv-Room Class# 1022 Jones 412 101-07 1022 Jones 412 143-01 1022 Jones 412 159-02 4123 Smith 216 201-01 4123 Smith 216 211-02 4123 Smith 216 214-01 - Second Normal Form: Eliminate Redundant Data
Note the multiple Class# values for each Student# value in the above table. Class# is not functionally dependent on Student# (primary key), so this relationship is not in second normal form.
The following two tables demonstrate second normal form:
Students:
Collapse this tableExpand this tableStudent# Advisor Adv-Room 1022 Jones 412 4123 Smith 216
Registration:
Collapse this tableExpand this tableStudent# Class# 1022 101-07 1022 143-01 1022 159-02 4123 201-01 4123 211-02 4123 214-01 - Third Normal Form: Eliminate Data Not Dependent On Key
In the last example, Adv-Room (the advisor's office number) is functionally dependent on the Advisor attribute. The solution is to move that attribute from the Students table to the Faculty table, as shown below:
Students:
Collapse this tableExpand this tableStudent# Advisor 1022 Jones 4123 Smith
Faculty:
Collapse this tableExpand this tableName Room Dept Jones 412 42 Smith 216 42
Numeric Validation
var charCode = (evt.which != undefined) ? evt.which : evt.keyCode;
if((charCode >= 48 && charCode <= 57) || charCode == 8 || charCode == 46)
return true;
return false;
}
onkeypress="return NumericKeyEvent(event);